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.



38
39
40
41
# File 'lib/nagare.rb', line 38

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



56
57
58
59
60
61
62
# File 'lib/nagare.rb', line 56

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

._optionsObject



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

def self._options
  @options ||= {}
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

.options(options) ⇒ Object



34
35
36
# File 'lib/nagare.rb', line 34

def self.options(options)
  @options = options
end

Instance Method Details

#as_json(options = nil) ⇒ Object



64
65
66
# File 'lib/nagare.rb', line 64

def as_json(options = nil)
  attributes
end

#attributesObject



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/nagare.rb', line 43

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

  if !self.class._options.fetch(:nil, false)
    attributes.compact
  else
    attributes
  end
end