Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Query string methods

  • Loading branch information...
commit 3222a7ad4827606b89859191d430776e9e280bf9 1 parent 2687b2d
@wagenet wagenet authored
Showing with 44 additions and 2 deletions.
  1. +44 −2 lib/tableless.rb
View
46 lib/tableless.rb
@@ -30,10 +30,10 @@ module ActiveRecord
module Tableless
def self.included( base ) #:nodoc:
- base.send( :extend, ClassMethods )
+ base.send( :extend, ActsMethods )
end
- module ClassMethods #:nodoc:
+ module ActsMethods #:nodoc:
# A model that needs to be tableless will call this method to indicate
# it.
@@ -47,6 +47,7 @@ def has_no_table
# extend
extend ActiveRecord::Tableless::SingletonMethods
+ extend ActiveRecord::Tableless::ClassMethods
# include
include ActiveRecord::Tableless::InstanceMethods
@@ -80,8 +81,32 @@ def #{m}
end
+ module ClassMethods
+
+ def from_query_string(query_string)
+ unless query_string.blank?
+ params = query_string.split('&').collect do |chunk|
+ next if chunk.empty?
+ key, value = chunk.split('=', 2)
+ next if key.empty?
+ value = value.nil? ? nil : CGI.unescape(value)
+ [ CGI.unescape(key), value ]
+ end.compact.to_h
+
+ new(params)
+ else
+ new
+ end
+ end
+
+ end
+
module InstanceMethods
+ def to_query_string(prefix = nil)
+ attributes.to_a.collect{|(name,value)| escaped_var_name(name, prefix) + "=" + escape_for_url(value) if value }.compact.join("&")
+ end
+
%w(save destroy).each do |m|
eval %{
def #{m}
@@ -91,6 +116,23 @@ def #{m}
}
end
+ private
+
+ def escaped_var_name(name, prefix = nil)
+ prefix ? "#{URI.escape(prefix)}[#{URI.escape(name)}]" : URI.escape(name)
+ end
+
+ def escape_for_url(value)
+ case value
+ when true then "1"
+ when false then "0"
+ when nil then ""
+ else URI.escape(value.to_s)
+ end
+ rescue
+ ""
+ end
+
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.