Class: Garage::Representer::Definition

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

Direct Known Subclasses

Collection

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Definition

Returns a new instance of Definition.



133
134
135
136
# File 'lib/garage/representer.rb', line 133

def initialize(name, options={})
  @name = name
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



131
132
133
# File 'lib/garage/representer.rb', line 131

def options
  @options
end

Instance Method Details

#encode(object, responder, selector = nil) ⇒ Object



154
155
156
157
# File 'lib/garage/representer.rb', line 154

def encode(object, responder, selector = nil)
  value = object.send(@name)
  encode_value(value, responder, selector)
end

#encode_value(value, responder, selector) ⇒ Object



159
160
161
162
163
164
165
166
167
# File 'lib/garage/representer.rb', line 159

def encode_value(value, responder, selector)
  if value.is_a?(Garage::Representer)
    responder.encode_to_hash(value, partial: true, selector: selector)
  elsif primitive?(value)
    value
  else
    raise NonEncodableValue, "#{value.class} can not be encoded directly. Forgot to include Garage::Representer?"
  end
end

#nameObject



150
151
152
# File 'lib/garage/representer.rb', line 150

def name
  (@options[:as] || @name).to_s
end

#primitive?(value) ⇒ Boolean

Returns:

  • (Boolean)


169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/garage/representer.rb', line 169

def primitive?(value)
  [
    ActiveSupport::TimeWithZone,
    Date,
    Time,
    Bignum,
    Fixnum,
    Float,
    Hash,
    Array,
    String,
    NilClass,
    TrueClass,
    FalseClass,
    Symbol,
  ].any? {|k| value.is_a?(k) }
end

#requires_select?Boolean

Returns:

  • (Boolean)


138
139
140
# File 'lib/garage/representer.rb', line 138

def requires_select?
  @options[:selectable]
end

#selectable?(*args) ⇒ Boolean

Returns:

  • (Boolean)


142
143
144
145
146
147
148
# File 'lib/garage/representer.rb', line 142

def selectable?(*args)
  if boolean?(@options[:selectable])
    @options[:selectable]
  else
    @options[:selectable].call(*args)
  end
end