Refactor add_property

Change implementation of the add_property method which allows for
dynamically adding attributes from outside the gem. We made it
simpler to construct the args needed for this method and refactored
the logic and tests.
This commit is contained in:
Michael Mitchell + Chris Stringer 2013-03-22 15:43:28 -07:00 committed by Jessica Lynn Suttles
parent 5deb796829
commit e8be12b66e
3 changed files with 33 additions and 11 deletions

View file

@ -28,14 +28,18 @@ module Microformats2
def parse_properties
PropertyParser.parse(@element.children).each do |property|
add_property(property)
assign_property(property)
end
end
def add_property(property)
save_property_name(property.method_name)
define_method(property.method_name)
set_value(property.method_name, property)
def add_property(property_class, value)
# NOTE: Might want to DRY this up with what is in PropertyParser
prefix = property_class.split("-").first
# find ruby class for kind of property
klass = Microformats2::Property::PREFIX_CLASS_MAP[prefix]
# We don't have a nokogiri element so pass in nil
property = klass.new(nil, property_class, value)
assign_property(property)
end
def parse_implied_properties
@ -68,6 +72,12 @@ module Microformats2
private
def assign_property(property)
save_property_name(property.method_name)
define_method(property.method_name)
set_value(property.method_name, property)
end
def to_method_name(html_class)
# p-class-name -> class_name
mn = html_class.downcase.split("-")[1..-1].join("_")

View file

@ -3,9 +3,10 @@ module Microformats2
class Foundation
attr_reader :method_name
def initialize(element, html_class)
def initialize(element, html_class, string_value=nil)
@element = element
@method_name = to_method_name(html_class)
@string_value = string_value
end
def parse
@ -15,7 +16,7 @@ module Microformats2
end
def to_s
@to_s ||= value_class_pattern || element_value || text_value
@to_s ||= string_value || value_class_pattern || element_value || text_value
end
def format
@ -52,6 +53,10 @@ module Microformats2
@element.inner_text.gsub(/\n+/, " ").gsub(/\s+/, " ").strip
end
def string_value
@string_value
end
def attribute
attr_map[@element.name]
end
@ -71,6 +76,7 @@ module Microformats2
end
def format_classes
return [] unless @element
@format_classes = @element.attribute("class").to_s.split.select do |html_class|
html_class =~ Format::CLASS_REG_EXP
end

View file

@ -75,11 +75,17 @@ describe Microformats2::Collection do
end
describe "Format.add_property" do
let(:value) { "bar" }
before do
@collection.first.add_property("p-foo", value)
end
it "creates the attr" do
fake_element = OpenStruct.new(inner_text: "dork")
fake_text_object = Microformats2::Property::Text.new(fake_element, "p-foo")
@collection.first.add_property(fake_text_object)
@collection.first.foo.to_s.should == "dork"
@collection.first.foo.to_s.should == value
end
it "allows json output of the attribute" do
@collection.first.to_json.should include(value)
end
end
end