Class: Former::Builder

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(html) ⇒ Builder

Returns a new instance of Builder.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/former/builder.rb', line 8

def initialize(html)
  @html = Nokogiri::HTML.parse(html)

  matches = {}
  self.class.queries.each { |path, qs|
    @html.search(path).each { |node| 
      # if all we need is the text, only include text kids
      if qs.length == 1 and qs.first[:query] == :text
        node.traverse { |e| matches[e] = qs if e.text? and not matches.keys.include? e }
      else
        # otherwise, ignore just text requests
        matches[node] = qs.select { |q| q[:query] != :text }
      end
    }
  }

  @editable = []
  @html.traverse_prefix { |e|
    (matches[e] || []).each { |query| 
      @editable << Element.new(e, query[:query], @editable.length, query[:block]) 
    }
  }
end

Class Attribute Details

.queriesObject

Returns the value of attribute queries.



5
6
7
# File 'lib/former/builder.rb', line 5

def queries
  @queries
end

Instance Attribute Details

#editableObject (readonly)

Returns the value of attribute editable.



6
7
8
# File 'lib/former/builder.rb', line 6

def editable
  @editable
end

Class Method Details

.attr(elem, attr, &block) ⇒ Object



60
61
62
63
64
# File 'lib/former/builder.rb', line 60

def self.attr(elem, attr, &block)
  @queries ||= {}
  @queries[elem] ||= []
  @queries[elem] << { :query => attr, :block => block }
end

.text(*elems, &block) ⇒ Object



66
67
68
69
# File 'lib/former/builder.rb', line 66

def self.text(*elems, &block)
  attr("text()", :text, &block) if elems.length == 0
  elems.each { |elem| attr(elem, :text, &block) }
end

Instance Method Details

#[]=(index, value) ⇒ Object



49
50
51
# File 'lib/former/builder.rb', line 49

def []=(index, value)
  @editable[index].set_value value
end

#each(&block) ⇒ Object



32
33
34
# File 'lib/former/builder.rb', line 32

def each(&block)
  @editable.each { |e| block.call(e) }
end

#set_values(vals) ⇒ Object

vals should be { :former_0 => ‘value’, :former_1 => ‘value two’, … }



54
55
56
57
58
# File 'lib/former/builder.rb', line 54

def set_values(vals)
  vals.each { |key, value|
    self[key.to_s.split('_').last.to_i] = value
  }
end

#to_form_htmlObject



36
37
38
# File 'lib/former/builder.rb', line 36

def to_form_html
  @editable.map(&:to_form_html).join("\n")
end

#to_htmlObject



44
45
46
47
# File 'lib/former/builder.rb', line 44

def to_html
  # nokogiri pads w/ xhtml/body elements
  @html.search("//body").first.children.map(&:to_html).join
end

#to_jsonObject



40
41
42
# File 'lib/former/builder.rb', line 40

def to_json
  "[" + @editable.map(&:to_json).join(",") + "]"
end