Class: RailsViewAdapters::AdapterBase

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_view_adapters/adapter_base.rb

Overview

Base class on which adapters are defined.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(internals, extras) ⇒ AdapterBase

Returns a new instance of AdapterBase.



45
46
47
48
49
50
# File 'lib/rails_view_adapters/adapter_base.rb', line 45

def initialize(internals, extras)
  @internals = internals
  @extras = extras
  @public_hash = nil
  @params_hash = nil
end

Class Method Details

.from_model(model) ⇒ Object

Create an instance from an ActiveRecord model.

Parameters:

  • model (ActiveRecord::AdapterBase)

Returns:

  • the adapter



16
17
18
19
20
21
22
# File 'lib/rails_view_adapters/adapter_base.rb', line 16

def self.from_model(model)
  internals = {}
  model_fields.each do |field|
    internals[field] = model.send(field)
  end
  new(internals, {})
end

.from_public(public) ⇒ Object

Create an instance from a public representation.

Parameters:

  • public (ActionController::Parameters)

Returns:

  • the adapter



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rails_view_adapters/adapter_base.rb', line 27

def self.from_public(public)
  internals = {}
  simple_maps.each do |model_field, public_field|
    internals[model_field] = public[public_field]
  end

  extras = {}
  (public.keys.map(&:to_sym) - public_fields).each do |extra_key|
    extras[extra_key] = public[extra_key]
  end

  from_maps.each do |public_field, process|
    internals.merge!(process.call(public[public_field]))
  end

  new(internals, extras)
end

Instance Method Details

#to_json(options = {}) ⇒ Object



56
57
58
# File 'lib/rails_view_adapters/adapter_base.rb', line 56

def to_json(options = {})
  to_public_hash.to_json(options)
end

#to_model_hashObject



60
61
62
# File 'lib/rails_view_adapters/adapter_base.rb', line 60

def to_model_hash
  @internals
end

#to_params_hashObject



52
53
54
# File 'lib/rails_view_adapters/adapter_base.rb', line 52

def to_params_hash
  @params_hash ||= to_model_hash.merge(@extras.symbolize_keys) {|_key, lhs, _rhs| lhs }
end

#to_public_hashObject



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

def to_public_hash
  unless @public_hash
    @public_hash = {}
    simple_maps.each do |model_field, public_field|
      @public_hash[public_field] = @internals[model_field]
    end
    to_maps.each do |model_field, process|
      @public_hash.merge!(process.call(@internals[model_field])) do |k, l, r|
        merge_strategy.call(k, l, r)
      end
    end
  end
  @public_hash
end