Skip to content

Commit

Permalink
Support :to_param option to specify how records map to params.
Browse files Browse the repository at this point in the history
  • Loading branch information
nakajima committed Feb 3, 2009
1 parent 32384af commit 63a6bb0
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
12 changes: 11 additions & 1 deletion lib/sinatras-hat/maker.rb
Expand Up @@ -92,6 +92,15 @@ def only(*actions)
end
end

# A way to determine a record's representation in the database
def to_param(name=nil)
if name
options[:to_param] = name
else
options[:to_param]
end
end

# A list of actions to protect via basic auth. Protected actions
# will have the authenticator block called before they are handled.
def protect(*actions)
Expand Down Expand Up @@ -129,9 +138,10 @@ def options
:only => Set.new(Maker.actions.keys),
:parent => nil,
:finder => proc { |model, params| model.all },
:record => proc { |model, params| model.find_by_id(params[:id]) },
:record => proc { |model, params| model.send("find_by_#{to_param}", params[:id]) },
:protect => [ ],
:formats => { },
:to_param => :id,
:credentials => { :username => 'username', :password => 'password', :realm => "The App" },
:authenticator => proc { |username, password| [username, password] == [:username, :password].map(&credentials.method(:[])) }
}
Expand Down
2 changes: 1 addition & 1 deletion lib/sinatras-hat/resource.rb
Expand Up @@ -17,7 +17,7 @@ def path(suffix, record=nil)
end

path = clean(path + suffix)
path.gsub!(/:(\w+)/) { parents.pop.id } if record
path.gsub!(/:(\w+)/) { parents.pop.send(@maker.to_param) } if record
path
end

Expand Down
15 changes: 15 additions & 0 deletions spec/maker_spec.rb
Expand Up @@ -147,6 +147,21 @@ class Comment; end
end
end

describe ":to_param" do
it "is :id by default" do
maker.options[:to_param].should == :id
end

it "is methodized" do
maker.to_param.should == :id
end

it "has methodized setter" do
maker.to_param :permalink
maker.to_param.should == :permalink
end
end

describe ":parent" do
it "is nil" do
maker.options[:parent].should be_nil
Expand Down

0 comments on commit 63a6bb0

Please sign in to comment.