Class: Nagare::Item

Inherits:
Object
  • Object
show all
Defined in:
lib/nagare.rb

Direct Known Subclasses

Collection

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, context) ⇒ Item

Returns a new instance of Item.



30
31
32
33
# File 'lib/nagare.rb', line 30

def initialize(object, context)
  @object = object
  @context = context
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, *args) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/nagare.rb', line 42

def method_missing(key, *args)
  if context.respond_to?(key)
    context.send(key, *args)
  else
    super
  end
end

Class Method Details

._attributesObject



6
7
8
# File 'lib/nagare.rb', line 6

def self._attributes
  @attributes ||= []
end

.attributes(*attributes) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/nagare.rb', line 10

def self.attributes(*attributes)
  @attributes = _attributes.concat(attributes)

  attributes.each do |attribute|
    define_method(attribute) do
      if object.respond_to?(attribute)
        object.send(attribute)
      elsif context.respond_to?(attribute)
        context.send(attribute)
      end
    end
  end
end

.inherited(base) ⇒ Object



24
25
26
27
28
# File 'lib/nagare.rb', line 24

def self.inherited(base)
  base.instance_variable_set(:@attributes, @attributes.dup) if @attributes

  super
end

Instance Method Details

#as_json(options = nil) ⇒ Object



50
51
52
# File 'lib/nagare.rb', line 50

def as_json(options = nil)
  attributes
end

#attributesObject



35
36
37
38
39
40
# File 'lib/nagare.rb', line 35

def attributes
  self.class._attributes.inject({}) do |hash, attribute|
    hash[attribute.to_s] = send(attribute)
    hash
  end.compact
end