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.



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

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



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/locomotive/presentable.rb', line 66

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

      if _options[:if].blank? || self.instance_eval(&_options[:if])
        value = self.send(meth.to_sym)

        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



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

def attributes=(values)
  return unless values

  @_attributes = values # memoize them for the callbacks

  run_callbacks :set_attributes do
    _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



87
88
89
# File 'lib/locomotive/presentable.rb', line 87

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

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

Initializer



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

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

  self.after_initialize
end

#property_optionsObject



99
100
101
# File 'lib/locomotive/presentable.rb', line 99

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

#settersList

Return the list of setters.

Returns:

  • (List)

    Array of method names



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

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