Class: SimpleAttribute::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_attribute/builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(context, options = {}) ⇒ Builder

Initialize base attribute



4
5
6
7
8
# File 'lib/simple_attribute/builder.rb', line 4

def initialize(context, options={})
  @context  = context
  @options  = options
  @renderer = options.fetch :as, guess_renderer
end

Instance Method Details

#base_rendererObject

Base attribute renderer



11
12
13
# File 'lib/simple_attribute/builder.rb', line 11

def base_renderer
  'SimpleAttribute::Attributes::Base'.safe_constantize
end

#find_renderer(renderer) ⇒ Object

Find attribute renderer



24
25
26
27
28
29
30
31
32
# File 'lib/simple_attribute/builder.rb', line 24

def find_renderer(renderer)
  namespace = @options[:namespace]
  renderer  = "#{renderer}".classify
  custom    = "#{namespace}::#{renderer}Attribute".safe_constantize
  custom    = "#{renderer}Attribute".safe_constantize if custom.nil?
  builtin   = "SimpleAttribute::Attributes::#{renderer}".safe_constantize if custom.nil?

  custom || builtin || base_renderer
end

#guess_rendererObject

Guess renderer



16
17
18
19
20
21
# File 'lib/simple_attribute/builder.rb', line 16

def guess_renderer
  record = @options[:record]
  attrib = @options[:attribute]

  SimpleAttribute::Matcher.new(record, attrib).match
end

#renderObject

Render



43
44
45
46
47
48
# File 'lib/simple_attribute/builder.rb', line 43

def render
  @rendered_attribute ||= begin
    html = Array(@renderer).map { |w| render_attribute(w) }
    html.reject(&:blank?).join.html_safe
  end
end

#render_attribute(renderer) ⇒ Object

Render attribute



35
36
37
38
39
40
# File 'lib/simple_attribute/builder.rb', line 35

def render_attribute(renderer)
  renderer = find_renderer renderer
  options  = @options.except(:as)

  renderer.new(@context, options).render
end