Class: Garage::Representer::Definition

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

Direct Known Subclasses

Collection

Constant Summary collapse

PRIMITIVE_CLASSES =
[
  ActiveSupport::TimeWithZone,
  Date,
  Time,
  Integer,
  Float,
  Hash,
  Array,
  String,
  NilClass,
  TrueClass,
  FalseClass,
  Symbol,
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Definition.



135
136
137
138
# File 'lib/garage/representer.rb', line 135

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

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



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

def options
  @options
end

Instance Method Details

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



156
157
158
159
# File 'lib/garage/representer.rb', line 156

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

#encode_value(value, responder, selector) ⇒ Object



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

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



152
153
154
# File 'lib/garage/representer.rb', line 152

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

#primitive?(value) ⇒ Boolean

Returns:

  • (Boolean)


186
187
188
# File 'lib/garage/representer.rb', line 186

def primitive?(value)
  PRIMITIVE_CLASSES.any? {|k| value.is_a?(k) }
end

#requires_select?Boolean

Returns:

  • (Boolean)


140
141
142
# File 'lib/garage/representer.rb', line 140

def requires_select?
  @options[:selectable]
end

#selectable?(*args) ⇒ Boolean

Returns:

  • (Boolean)


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

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