Class: Boxxspring::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/boxxspring/resources/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}, associations = {}) {|_self| ... } ⇒ Base

Returns a new instance of Base.

Yields:

  • (_self)

Yield Parameters:



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/boxxspring/resources/base.rb', line 37

def initialize( attributes = {}, associations = {} )
   attributes.symbolize_keys!
   @attributes = attributes
   attributes.dup.each do | key, value |
     send( "#{key}=", value ) if respond_to?( "#{key}=" )
   end
   associations.each do | key, value |
     self.instance_variable_set( "@_#{key}", value )
   end
   yield self if block_given?
end

Class Method Details

.field(name, options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/boxxspring/resources/base.rb', line 5

def self.field( name, options = {} )
  
  class_eval(
    "def #{name}(); " +
       "@#{name} || " +
         ( options[ :default ].nil? ?
            "nil" :
            ( options[ :default ].is_a?( String ) ? 
                "'#{options[ :default ]}'" : 
                  "#{options[ :default ]}" ) ) + ";" +
    "end;" +
    " " +
    "attr_writer :#{name};",
    __FILE__, 
    __LINE__
  )

end

.has_many(name, options = {}) ⇒ Object



31
32
33
34
35
# File 'lib/boxxspring/resources/base.rb', line 31

def self.has_many( name, options = {} )  
  define_method name do 
    self.instance_variable_get( "@_#{name}" ) || options[ :default ]
  end
end

.has_one(name, options = {}) ⇒ Object



24
25
26
27
28
29
# File 'lib/boxxspring/resources/base.rb', line 24

def self.has_one( name, options = {} )
  define_method name do 
    associations = self.instance_variable_get( "@_#{name.to_s.pluralize}" )
    associations.present? ? associations.first : options[ :default]
  end
end