Module: SimpleMapper::Properties

Defined in:
lib/simple_mapper/default_plugins/properties.rb

Overview

Properties sets up a structure of properties such that:

  1. You name an identifier and several properties that will be used in your model, and

  2. properties do not include the identifier

Properties are accessed and set through method_missing, simply using instance variables to store each property value. If you wish, you can define your own accessor method for any property and it will be used instead.

The methods data and data= are provided and perform the usual logical behavior for a model that has properties == it receives a hash and calls the appropriate methods on the object according to the keys in that hash, when they match up with a defined property. data simply calls to_hash, which performs the opposite, simply collecting the properties into a hash by calling the appropriate accessor methods.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/simple_mapper/default_plugins/properties.rb', line 60

def method_missing(method, *args)
  if self.class.properties.include?(method)
    instance_variable_get("@#{method}")
  elsif method.to_s =~ /=$/ && self.class.properties.include?(method.to_s.gsub(/=/, '').to_sym)
    instance_variable_set("@#{method.to_s.gsub(/=/, '')}", *args)
  else
    super
  end
end

Class Method Details

.included(base) ⇒ Object



15
16
17
# File 'lib/simple_mapper/default_plugins/properties.rb', line 15

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#data(options = {}) ⇒ Object



38
39
40
# File 'lib/simple_mapper/default_plugins/properties.rb', line 38

def data(options={})
  to_hash(options)
end

#data=(data) ⇒ Object Also known as: update_data

Sets the data into the object. This is provided as a default method, but your model can overwrite it any way you want. For example, you could set the data to some other object type, or to a Marshalled storage. The type of data you receive will depend on the format and parser you use. Of course you could make up your own spin-off of one of those, too.

Raises:

  • (TypeError)


46
47
48
49
# File 'lib/simple_mapper/default_plugins/properties.rb', line 46

def data=(data)
  raise TypeError, "data must be a hash" unless data.is_a?(Hash)
  data.each {|k,v| instance_variable_set("@#{k}", v)}
end

#identifierObject



56
57
58
# File 'lib/simple_mapper/default_plugins/properties.rb', line 56

def identifier
  instance_variable_get("@#{self.class.identifier}")
end

#to_hash(options = {}) ⇒ Object



52
53
54
# File 'lib/simple_mapper/default_plugins/properties.rb', line 52

def to_hash(options={})
  self.class.properties.inject({}) {|h,k| h[k] = instance_variable_get("@#{k}"); h}
end