Module: Wrest::Components::AttributesContainer::InstanceMethods

Defined in:
lib/wrest/components/attributes_container.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_sym, *arguments) ⇒ Object

Creates getter, setter and query methods for attributes on the first call.



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/wrest/components/attributes_container.rb', line 157

def method_missing(method_sym, *arguments)
  method_name = method_sym.to_s
  attribute_name = method_name.gsub(/(\?$)|(=$)/, '')

  if @attributes.include?(attribute_name.to_sym) || method_name.last == '='
    case method_name.last
    when '='
      @interface.module_eval AttributesContainer.build_attribute_setter(attribute_name)
    when '?'
      @interface.module_eval AttributesContainer.build_attribute_queryer(attribute_name)
    else
      @interface.module_eval AttributesContainer.build_attribute_getter(attribute_name)
    end
    send(method_sym, *arguments)
  else
    super(method_sym, *arguments)
  end
end

Instance Method Details

#[](key) ⇒ Object



143
144
145
# File 'lib/wrest/components/attributes_container.rb', line 143

def [](key)
  @attributes[key.to_sym]
end

#[]=(key, value) ⇒ Object



147
148
149
# File 'lib/wrest/components/attributes_container.rb', line 147

def []=(key, value)
  @attributes[key.to_sym] = value
end

#initialize(attributes = {}) ⇒ Object

Sets up any class to act like an attributes container by creating two variables, @attributes and @interface. Remember not to use these two variable names when using AttributesContainer in your own class.



133
134
135
136
137
138
139
140
141
# File 'lib/wrest/components/attributes_container.rb', line 133

def initialize(attributes = {})
  @attributes = attributes.symbolize_keys
  self.class.typecast_map.each do |key, typecaster|
    value = @attributes[key]
    @attributes[key] = typecaster.call(value) if value.is_a?(String)
  end
  @interface = Module.new
  self.extend @interface
end

#respond_to?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


151
152
153
# File 'lib/wrest/components/attributes_container.rb', line 151

def respond_to?(method_name, include_private = false)
  super(method_name, include_private) ? true : @attributes.include?(method_name.to_s.gsub(/(\?$)|(=$)/, '').to_sym)
end