class SimpleRepresenter::Field

Attributes

field[R]
options[R]

Public Class Methods

new(field, options) click to toggle source
# File lib/simple_representer/field.rb, line 7
def initialize(field, options)
  @field = field.to_sym
  @options = options
end

Public Instance Methods

call(representer) click to toggle source
# File lib/simple_representer/field.rb, line 12
def call(representer)
  return if options[:if] && !representer.instance_exec(&options[:if])

  value = process(representer)
  value = options[:default] if value.nil?
  value = nested_representer(value) if options[:representer] && !value.nil?

  build_field(value)
end

Private Instance Methods

build_field(value) click to toggle source
# File lib/simple_representer/field.rb, line 30
def build_field(value)
  return if value.nil? && !options.fetch(:render_nil, false)

  [(options[:as] || field).to_sym, value]
end
nested_representer(value) click to toggle source
# File lib/simple_representer/field.rb, line 24
def nested_representer(value)
  return options[:representer].for_collection(value).to_h if value.is_a?(Array)

  options[:representer].new(value).to_h
end