Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert model objects into request parameters with a overrideable helper method #21

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 11 additions & 2 deletions lib/her/model/orm.rb
Expand Up @@ -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]
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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
35 changes: 35 additions & 0 deletions spec/model/orm_spec.rb
Expand Up @@ -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