Created
February 5, 2010 20:25
-
-
Save reactormonk/296187 to your computer and use it in GitHub Desktop.
This file contains 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
$LOAD_PATH.unshift(File.expand_path("#{__FILE__}/../../lib")) # Add PROJECT/lib to $LOAD_PATH | |
require 'stylist' |
This file contains 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
BareTest.suite "Stylist" do | |
suite "Stylist" do | |
suite "Style finding" do | |
setup do | |
class Foo; end | |
module Stylist; class Foo; def initialize(*args); end; end; end | |
module Bar; class Foo; end; end | |
module Stylist; module Bar; class Foo; def initialize(*args); end; end; end; end | |
end | |
setup :class, "a class without namespace" do | |
@model = Foo.new | |
@result = Stylist::Foo | |
end | |
setup :class, "a class with namespace" do | |
@model = Bar::Foo.new | |
@result = Stylist::Bar::Foo | |
end | |
assert "#style_for finds the right Stylist object for :class" do | |
equal @result, ::Stylist.send(:style_for, @model) | |
end | |
assert "#new_stylist_for creates a new Style instance" do | |
equal @result.class, ::Stylist.new_stylist_for(@model) | |
end | |
end | |
end | |
end |
This file contains 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
module Stylist | |
def new_stylist_for(model, context={}) | |
style_for(model).new(model, context) | |
end | |
private | |
# @param name<String> The name of the constant to get, e.g. "Merb::Router". | |
# | |
# @return <Object> The constant corresponding to the name. | |
def full_const_get(name) | |
list = name.split("::") | |
list.shift if list.first.nil? || list.first.strip.empty? | |
obj = ::Object | |
list.each do |x| | |
# This is required because const_get tries to look for constants in the | |
# ancestor chain, but we only want constants that are HERE | |
obj = obj.const_defined?(x) ? obj.const_get(x) : obj.const_missing(x) | |
end | |
obj | |
end | |
def style_for(model) | |
begin | |
full_const_get(model.class.to_s) | |
rescue NameError | |
nil | |
end | |
end | |
extend self | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment