Created
July 10, 2012 05:55
-
-
Save AMekss/3081435 to your computer and use it in GitHub Desktop.
Rails view helper for extracting value by path string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding : utf-8 -*- | |
module ApplicationHelper | |
def read_value_from(object, path_string, alt_value=nil) | |
return alt_value unless object && path_string | |
value = object | |
path_string.split(".").each do |path_component| | |
return alt_value unless value.respond_to?(path_component.to_sym) | |
value = value.send(path_component.to_sym) | |
end | |
value | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding : utf-8 -*- | |
require 'spec_helper' | |
class ChainTestTargetNode | |
def value | |
"test_value_from_target" | |
end | |
def nil_value | |
nil | |
end | |
end | |
class ChainTestMidNode | |
def chain_up | |
ChainTestTargetNode.new | |
end | |
end | |
class ChainTestSourceNode | |
def chain_up | |
ChainTestMidNode.new | |
end | |
def value | |
"test_value_from_self" | |
end | |
end | |
describe ApplicationHelper do | |
context "read_value_from method" do | |
let(:alt_value){'alt value text'} | |
let(:test_object){ ChainTestSourceNode.new } | |
it "should return alt value if object or path or both are nil" do | |
helper.read_value_from(nil, nil, alt_value).should == alt_value | |
helper.read_value_from(nil, 'test.test.test', alt_value).should == alt_value | |
helper.read_value_from({}, nil, alt_value).should == alt_value | |
end | |
it "should return nil for alt value if isn't specified" do | |
helper.read_value_from(nil, nil).should be_nil | |
end | |
it "should return alt value unless object respond to given path" do | |
helper.read_value_from(test_object, "chain_up.chain_up.aaaa", alt_value).should == alt_value | |
helper.read_value_from(test_object, "chain_up.bbbb.aaaa", alt_value).should == alt_value | |
helper.read_value_from(test_object, "cccc.bbbb.aaaa", alt_value).should == alt_value | |
end | |
it "should return value if object respond to given path" do | |
helper.read_value_from(test_object, "chain_up.chain_up.value").should == "test_value_from_target" | |
helper.read_value_from(test_object, "value").should == "test_value_from_self" | |
end | |
it "it should return nil if object respond to given path and return nil" do | |
helper.read_value_from(test_object, "chain_up.chain_up.nil_value", alt_value).should be_nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment