Class: JsonCrudApi::Presenter

Inherits:
Object
  • Object
show all
Defined in:
lib/json-crud-api/presenter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Presenter

Returns a new instance of Presenter.



6
7
8
9
10
11
12
13
14
15
# File 'lib/json-crud-api/presenter.rb', line 6

def initialize(options)
  @model = options[:model]
  @exclude = options[:exclude]
  @include = options[:include]

  # Properties Cache
  @properties = { :render => {}, :parse => {} }

  throw "Model must be defined" if @model.nil?
end

Instance Attribute Details

#excludeObject

Returns the value of attribute exclude.



4
5
6
# File 'lib/json-crud-api/presenter.rb', line 4

def exclude
  @exclude
end

#includeObject

Returns the value of attribute include.



4
5
6
# File 'lib/json-crud-api/presenter.rb', line 4

def include
  @include
end

#modelObject

Returns the value of attribute model.



4
5
6
# File 'lib/json-crud-api/presenter.rb', line 4

def model
  @model
end

Instance Method Details

#filter_properties(parameter, method, operation) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/json-crud-api/presenter.rb', line 45

def filter_properties(parameter, method, operation)
  properties = []
  properties += parameter[:all] unless parameter[:all].nil?
  properties += parameter[operation] unless parameter[operation].nil?
  unless parameter[method].nil?
    properties += parameter[method][:all] unless parameter[method][:all].nil?
    properties += parameter[method][operation] unless parameter[method][operation].nil?
  end
  properties
end

#get_properties(method, operation) ⇒ Object



38
39
40
41
42
43
# File 'lib/json-crud-api/presenter.rb', line 38

def get_properties(method, operation)
  properties = @model.properties.map { |p| p.name.to_sym }
  properties -= filter_properties @exclude, method, operation unless @exclude.nil?
  properties += filter_properties @include, method, operation unless @include.nil?
  properties
end

#parse(data, operation = nil) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/json-crud-api/presenter.rb', line 26

def parse(data, operation = nil)
  return data.map {|d| parse(d, operation) } if data.is_a?(Array)

  unless @properties[:parse].has_key? operation
    @properties[:parse][operation] = get_properties(:parse, operation)
  end

  out = Hash.new
  data.each_pair { |k,v| out[k] = v if @properties[:parse][operation].include?(k) }
  out
end

#render(data, operation = nil) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/json-crud-api/presenter.rb', line 17

def render(data, operation = nil)
  return data.map {|d| render(d, operation) } if data.is_a?(Array)

  unless @properties[:render].has_key? operation
    @properties[:render][operation] = get_properties(:render, operation)
  end
  Hash[@properties[:render][operation].map { |p| [p, data.send(p)] }]
end