Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Tidied up rails url_writer host defaults.

  • Loading branch information...
commit 596e09cfab9a711a6740c4bb6be878196f302dd7 1 parent 932edf3
@playgood authored
Showing with 19 additions and 8 deletions.
  1. +4 −4 README.md
  2. +8 −4 lib/get_shorty.rb
  3. +7 −0 spec/active_record_helper.rb
View
8 README.md
@@ -53,14 +53,14 @@ For example:
_This assumes you have defined a Class `MyShortener` which respond to the method `shorten` with the parameter url_
-## Options
+## Parameters & Options
`has_short_url` has the following options:
-
+* `long_url_host` - this is required so the rails url_helper method work. Takes a string or a hash with a value for each environment.
* `:shortening_service` - default is Bitly::Client.connection - you can create your own (it just needs to be an object that responds to `.shorten(url)`)
-* `:short_url_method` - default is :short_url (most commonly a db column - but not neccesarily)
+* `:short_url_method` - default is :short_url (most commonly a db column - but not necessarily)
* `:long_url_method` - default is :generate_long_url - In a rails app this would probably be a resourceful route helper method for example page_url.
-* `long_url_host` - this is needed so the rails url_helper method work.
+
## Integration
View
12 lib/get_shorty.rb
@@ -22,12 +22,16 @@ def has_short_url(options={})
include ActionController::UrlWriter if defined?(ActionController )# non mvc - but need to know the url for model instance to persist the short_url.
@short_url_options = {:long_url_method => :generate_long_url, :short_url_method => :short_url}.update(options)
@shortening_serivce = options[:shortener_service] || Bitly::Client.connection
- @long_url_host = options[:long_url_host]
+ set_long_url_host options[:long_url_host]
end
# for Rails when using UrlWriter
- def get_long_url_host
- @long_url_host
+ def set_long_url_host(value)
+ self.default_url_options[:host] = if value.is_a?(Hash) && defined?(Rails)
+ value.stringify_keys[Rails.env]
+ else
+ value
+ end
end
end
@@ -56,7 +60,7 @@ def get_short_url(url=nil)
# Goes against the MVC conventions (although we are generating this for the purpose of creating a short_url for the database so it is to do with the Model.)
def generate_long_url()
begin
- send("#{self.class.name.downcase}_url", self, :host => self.class.get_long_url_host) unless self.new_record? # Can't generate the url until we have an id and title.
+ send("#{self.class.name.downcase}_url", self) unless self.new_record? # Can't generate the url until we have an id and title.
end
end
View
7 spec/active_record_helper.rb
@@ -12,6 +12,13 @@
set_bitly_configuration
class Post < ActiveRecord::Base
+ # to replicate rails url_writer
+ def self.default_url_options
+ {}
+ end
+
include GetShorty
has_short_url
+
+
end
Please sign in to comment.
Something went wrong with that request. Please try again.