Module: Locomotive::Presentable

Extended by:
ActiveSupport::Concern
Included in:
BasePresenter
Defined in:
lib/locomotive/presentable.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#after_initializeObject

Method called just after a presenter has been initialized. This method can be overridden.



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

def after_initialize
  # do nothing
end

#as_json(methods = nil) ⇒ Hash

Build the hash of the values of all the properties.

Parameters:

  • methods (Array) (defaults to: nil)

    (Optional) List of methods instead of using the default getters

Returns:

  • (Hash)

    The “attributes” of the object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/locomotive/presentable.rb', line 63

def as_json(methods = nil)
  methods ||= self.getters
  {}.tap do |hash|
    methods.each do |meth|
      value     = self.send(meth.to_sym)
      _options  = self.property_options[meth]

      if _options[:if].blank? || self.instance_eval(&_options[:if])
        if !value.nil? || (_options && !!_options[:allow_nil])
          hash[meth] = value
        end
      end
    end
  end
end

#attributes=(values) ⇒ Object

Set the attributes of the presenter. Only call the methods which the presenter can handle.

Parameters:

  • value (Hash)

    The attributes



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/locomotive/presentable.rb', line 39

def attributes=(values)
  run_callbacks :set_attributes do
    return unless values

    _values = values.stringify_keys

    self.setters.each do |name|
      if _values.has_key?(name)
        _options = self.property_options[name]

        if _options[:if].blank? || self.instance_eval(&_options[:if])
          self.send(:"#{name}=", _values[name])
        end
      end
    end
  end
end

#gettersList

Return the list of getters.

Returns:

  • (List)

    Array of method names



83
84
85
# File 'lib/locomotive/presentable.rb', line 83

def getters
  self.class.getters || []
end

#initialize(object, options = {}) ⇒ Object

Initializer



20
21
22
23
24
25
# File 'lib/locomotive/presentable.rb', line 20

def initialize(object, options = {})
  @source   = object
  @options  = options || {}

  self.after_initialize
end

#property_optionsObject



95
96
97
# File 'lib/locomotive/presentable.rb', line 95

def property_options
  self.class.property_options || {}
end

#settersList

Return the list of setters.

Returns:

  • (List)

    Array of method names



91
92
93
# File 'lib/locomotive/presentable.rb', line 91

def setters
  self.class.setters || []
end