Class: Microformat::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/microformat/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}, &block) ⇒ Attribute

Returns a new instance of Attribute.



7
8
9
10
11
12
13
14
15
# File 'lib/microformat/attribute.rb', line 7

def initialize(name, options = {}, &block)
  @name = name
  @options = options
  @attributes ||= {}
  if options[:format]
    @attributes.merge!(options[:format].attribute_definition.attributes)
  end
  block.yield(self) if block_given?
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



5
6
7
# File 'lib/microformat/attribute.rb', line 5

def attributes
  @attributes
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/microformat/attribute.rb', line 5

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/microformat/attribute.rb', line 5

def options
  @options
end

Instance Method Details

#attribute(name, options = {}, &block) ⇒ Object



17
18
19
20
21
# File 'lib/microformat/attribute.rb', line 17

def attribute(name, options = {}, &block)
  Attribute.new(name, options, &block).tap do |attribute|
    @attributes.merge!(name.to_sym => attribute)
  end
end

#cast(value, cast_to = nil) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/microformat/attribute.rb', line 41

def cast(value, cast_to = nil)
  value && case cast_to
  when :integer then value.to_s.strip.to_i
    when :decimal then value.to_s.strip.to_f
    when :string then value.to_s.strip
    else value
  end
end

#read_from(document) ⇒ Object



23
24
25
26
27
28
# File 'lib/microformat/attribute.rb', line 23

def read_from(document)
  selector = options[:selector] || ".#{@name}"
  sub_document = document.css(selector).first
  value = read_value_from(sub_document)
  AttributeMap.new(self, sub_document, { value: value })
end

#read_value_from(document) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/microformat/attribute.rb', line 30

def read_value_from(document)
  Array(options[:attribute] || "text").each do |attr|
    if attr == "text"
      return cast((document && document.text) || options[:default], options[:cast])
    elsif document[attr]
      return cast(document && document[attr], options[:cast])
    end
  end
  return options[:default]
end