Sha256: ad94b252b26e237cf6600c1d16de16382db948becd0b5bfa569716c1efadb44a

Contents?: true

Size: 1.6 KB

Versions: 47

Compression:

Stored size: 1.6 KB

Contents

module SugarCube
  # A subclass of Hash that allows its keys to be accessed and assigned by
  # method name.  Useful to quickly mock objects.  To that end, a
  # `NoMethodError` is raised anytime the key doesn't exist (getter or setter)
  #
  # You can convert an existing Hash or NSDictionary into a Anonymous using the
  # constructor `SugarCube::Anonymous[hash]`, or you can call `to_object` on a
  # dictionary or hash.
  #
  # @example
  #     obj = {
  #       'first_name': 'Katsuyoshi',  # strings
  #       company: 'Ito Soft Design',  # and symbols are supported
  #     }.to_object
  #
  #     obj.first_name
  #     # => 'Katsuyoshi'
  #     obj.company
  #     # => 'Ito Soft Design'
  #     obj.bla  # => raises NoMethodError
  #     obj.bla = 'bla'  # => raises NoMethodError
  class Anonymous < Hash

    def method_missing(symbol, *args)
      if args.size == 0
        key = symbol
        key = symbol.to_s unless self.include? key
        if self.include?(key)
          self[key] = self[key].to_object
          return self[key]
        end
      elsif args.size == 1 && /(.*)=$/ =~ symbol.to_s
        key = $1.to_sym
        key = key.to_s unless self.include? key
        if self.include?(key)
          return self[key] = args.first.to_object
        end
      end
      return super
    end

    def to_object
      self
    end

    # replace enumerable methods
    alias :anonymous_each :each
    
    def each
      anonymous_each {|k,v| yield k, v.to_object}
    end

  end

end

class NSObject

  def to_object
    self
  end

end

class NSDictionary

  def to_object
    SugarCube::Anonymous[self]
  end

end

Version data entries

47 entries across 47 versions & 1 rubygems

Version Path
sugarcube-1.4.3 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.4.2 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.4.1 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.4.0 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.11 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.10 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.9 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.8 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.7 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.6 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.5 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.4 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.3 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.2 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.1 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.3.0 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.1.0 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.0.7 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.0.6 lib/sugarcube-anonymous/anonymous.rb
sugarcube-1.0.5 lib/sugarcube-anonymous/anonymous.rb