Reputation: 349
When I do a mapping in active resource, its default request to the Ruby on Rails always automatically add the extension at the end of the url. For example: I want to get user resource from Ruby on Rails by mapping as below:
class user < ActiveResource::Base self.site = 'http://localhost:3000' end
And something that I need, I just want it pass the url without extension like
http://localhost:3000/userIn contrast it automatically adds the extension at the end of the url like
http://localhost:3000/user.xml
How can I omit the extension of the url when I make request from the active resource mapping?
Upvotes: 15
Views: 5159
Reputation: 833
At first, I did use @Joel AZEMAR's answer and it worked quite well until I started using PUT. Doing a PUT added in the .json/.xml.
A bit of research here, revealed that using the ActiveResource::Base#include_format_in_path
option worked far better for me.
Without include_format_in_path:
class Foo < ActiveResource::Base
self.site = 'http://localhost:3000'
end
Foo.element_path(1)
=> "/foo/1.json"
With include_format_in_path:
class Foo < ActiveResource::Base
self.include_format_in_path = false
self.site = 'http://localhost:3000'
end
Foo.element_path(1)
=> "/foo/1"
Upvotes: 17
Reputation: 2536
You can override methods of ActiveResource::Base
Add this lib in /lib/active_resource/extend/ directory don't forget uncomment
"config.autoload_paths += %W(#{config.root}/lib)" in config/application.rb
module ActiveResource #:nodoc:
module Extend
module WithoutExtension
module ClassMethods
def element_path_with_extension(*args)
element_path_without_extension(*args).gsub(/.json|.xml/,'')
end
def new_element_path_with_extension(*args)
new_element_path_without_extension(*args).gsub(/.json|.xml/,'')
end
def collection_path_with_extension(*args)
collection_path_without_extension(*args).gsub(/.json|.xml/,'')
end
end
def self.included(base)
base.class_eval do
extend ClassMethods
class << self
alias_method_chain :element_path, :extension
alias_method_chain :new_element_path, :extension
alias_method_chain :collection_path, :extension
end
end
end
end
end
end
in model
class MyModel < ActiveResource::Base
include ActiveResource::Extend::WithoutExtension
end
Upvotes: 4
Reputation: 2849
You can do this by overriding two ActiveResource's methods in your class:
class User < ActiveResource::Base
class << self
def element_path(id, prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}/#{id}#{query_string(query_options)}"
end
def collection_path(prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}"
end
end
self.site = 'http://localhost:3000'
end
Upvotes: 4