Class: Restful::Url

Inherits:
Object
  • Object
show all
Includes:
ActionController::UrlWriter
Defined in:
lib/restful/serializer.rb

Overview

Used to construct and attempt to call named routes by providing resource strings out of which a named route method name will be constructed:

Options:

  • :api_prefix => if we are constructing an url helper from a collection of resource names, prepend it with this prefix

  • :resources => a symbol, string or array of same describing segments of the helper method name. e.g. [:user, :comments] => user_comments (to which _url will be appended…)

  • :method => overrides the use of :resources and :api_prefix

  • :named_route_options => any additional options to be passed to the named_route when it is called (:id or :host for instance)

Example

Url.for(:api_prefix => :foo_service, :resources => [:user, :comments],
  :named_route_options => {:id => 1})

# => send("foo_service_user_comments_url", {:id => 1})
# which if it exists is likely to return something like:
# "http://example.com/user/1/comments"

Constant Summary collapse

@@initialized =
false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Url

Returns a new instance of Url.



76
77
78
79
# File 'lib/restful/serializer.rb', line 76

def initialize(options)
  self.options = options
  Url.initialize_default_url_options
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



54
55
56
# File 'lib/restful/serializer.rb', line 54

def options
  @options
end

Class Method Details

.for(options) ⇒ Object

Helper for generating url strings from resource options.



71
72
73
# File 'lib/restful/serializer.rb', line 71

def for(options)
  new(options).to_s
end

.initialize_default_url_optionsObject

Sets ActionController::UrlWriter.default_url_options from Restful.default_url_options. Attempting to do this during Rails initialization results in botched routing, presumably because of how ActionController::UrlWriter initializes when you include it into a class. So this method is called lazily.



63
64
65
66
67
68
# File 'lib/restful/serializer.rb', line 63

def initialize_default_url_options
  unless @@initialized
    self.default_url_options = Restful.default_url_options
    @@initialized = true
  end
end

Instance Method Details

#to_sObject



81
82
83
84
85
86
# File 'lib/restful/serializer.rb', line 81

def to_s
  url_for = [options[:method], 'url'] if options.include?(:method)
  url_for ||= [options[:api_prefix], options[:resources], 'url'].flatten.compact
  url_for = url_for.join('_').downcase
  send(url_for, *Array(options[:args])) if respond_to?(url_for) 
end