Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Convert model objects into request parameters with a overrideable hel…

…per method
  • Loading branch information...
commit e8542c9078f47a255742a868eb3cbf0a7ec20fd9 1 parent 0bd902b
@thomsbg thomsbg authored committed
Showing with 46 additions and 2 deletions.
  1. +11 −2 lib/her/model/orm.rb
  2. +35 −0 spec/model/orm_spec.rb
View
13 lib/her/model/orm.rb
@@ -100,7 +100,7 @@ def all(params={}) # {{{
def create(params={}) # {{{
resource = new(params)
wrap_in_hooks(resource, :create, :save) do |resource, klass|
- params = resource.instance_eval { @data }
+ params = resource.to_params
request(params.merge(:_method => :post, :_path => "#{build_request_path(params)}")) do |parsed_data|
resource.instance_eval do
@data = parsed_data[:data]
@@ -136,7 +136,7 @@ def save_existing(id, params) # {{{
# @user.save
# # Called via POST "/users"
def save # {{{
- params = @data.dup
+ params = to_params
resource = self
if @data[:id]
@@ -185,6 +185,15 @@ def destroy_existing(id, params={}) # {{{
new(parsed_data[:data])
end
end # }}}
+
+ # Convert into a hash of request parameters
+ #
+ # @example
+ # @user.to_params
+ # # => { :id => 1, :name => 'John Smith' }
+ def to_params # {{{
+ @data.dup
+ end # }}}
end
end
end
View
35 spec/model/orm_spec.rb
@@ -240,4 +240,39 @@ def organization=(organization)
@user.active.should be_false
end # }}}
end
+
+ context "saving resources with overridden to_params" do
+ before do
+ Her::API.setup :url => "https://api.example.com" do |builder|
+ builder.use Her::Middleware::FirstLevelParseJSON
+ builder.use Faraday::Request::UrlEncoded
+ builder.adapter :test do |stub|
+ stub.post("/users") do |env|
+ body = {
+ :id => 1,
+ :fullname => Faraday::Utils.parse_query(env[:body])['fullname']
+ }.to_json
+ [200, {}, body]
+ end
+ end
+ end
+
+ spawn_model "Foo::User" do
+ def to_params
+ { :fullname => "Lindsay Fünke" }
+ end
+ end
+ end
+
+ it "changes the request parameters for one-line resource creation" do
+ @user = Foo::User.create(:fullname => "Tobias Fünke")
+ @user.fullname.should == "Lindsay Fünke"
+ end
+
+ it "changes the request parameters for Model.new + #save" do
+ @user = Foo::User.new(:fullname => "Tobias Fünke")
+ @user.save
+ @user.fullname.should == "Lindsay Fünke"
+ end
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.