Class: Guillotine::ActiveRecordAdapter
- Defined in:
- lib/guillotine/adapters/active_record_adapter.rb
Defined Under Namespace
Classes: Url
Instance Method Summary collapse
-
#add(url, code = nil) ⇒ Object
Public: Stores the shortened version of a URL.
-
#clear(url) ⇒ Object
Public: Removes the assigned short code for a URL.
-
#code_for(url) ⇒ Object
Public: Retrieves the code for a given URL.
-
#find(code) ⇒ Object
Public: Retrieves a URL from the code.
-
#initialize(config) ⇒ ActiveRecordAdapter
constructor
A new instance of ActiveRecordAdapter.
- #select(field, query) ⇒ Object
- #setup ⇒ Object
Methods inherited from Adapter
Constructor Details
#initialize(config) ⇒ ActiveRecordAdapter
Returns a new instance of ActiveRecordAdapter.
7 8 9 |
# File 'lib/guillotine/adapters/active_record_adapter.rb', line 7 def initialize(config) Url.establish_connection config end |
Instance Method Details
#add(url, code = nil) ⇒ Object
Public: Stores the shortened version of a URL.
url - The String URL to shorten and store. code - Optional String code for the URL.
Returns the unique String code for the URL. If the URL is added multiple times, this should return the same code.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/guillotine/adapters/active_record_adapter.rb', line 18 def add(url, code = nil) if row = Url.select(:code).where(:url => url).first row[:code] else code ||= shorten url begin Url.create :url => url, :code => code rescue ActiveRecord::RecordNotUnique, ActiveRecord::StatementInvalid row = Url.select(:url).where(:code => code).first existing_url = row && row[:url] raise DuplicateCodeError.new(existing_url, url, code) end code end end |
#clear(url) ⇒ Object
Public: Removes the assigned short code for a URL.
url - The String URL to remove.
Returns nothing.
57 58 59 |
# File 'lib/guillotine/adapters/active_record_adapter.rb', line 57 def clear(url) Url.where(:url => url).delete_all end |
#code_for(url) ⇒ Object
Public: Retrieves the code for a given URL.
url - The String URL to lookup.
Returns the String code, or nil if none is found.
48 49 50 |
# File 'lib/guillotine/adapters/active_record_adapter.rb', line 48 def code_for(url) select :code, :url => url end |
#find(code) ⇒ Object
Public: Retrieves a URL from the code.
code - The String code to lookup the URL.
Returns the String URL.
39 40 41 |
# File 'lib/guillotine/adapters/active_record_adapter.rb', line 39 def find(code) select :url, :code => code end |
#select(field, query) ⇒ Object
72 73 74 75 76 |
# File 'lib/guillotine/adapters/active_record_adapter.rb', line 72 def select(field, query) if row = Url.select(field).where(query).first row[field] end end |
#setup ⇒ Object
61 62 63 64 65 66 67 68 69 70 |
# File 'lib/guillotine/adapters/active_record_adapter.rb', line 61 def setup conn = Url.connection conn.create_table :urls do |t| t.string :url t.string :code end conn.add_index :urls, :url, :unique => true conn.add_index :urls, :code, :unique => true end |