Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Query string methods

  • Loading branch information...
commit 3222a7ad4827606b89859191d430776e9e280bf9 1 parent 2687b2d
Peter Wagenet wagenet authored

Showing 1 changed file with 44 additions and 2 deletions. Show diff stats Hide diff stats

  1. +44 2 lib/tableless.rb
46 lib/tableless.rb
@@ -30,10 +30,10 @@ module ActiveRecord
30 30 module Tableless
31 31
32 32 def self.included( base ) #:nodoc:
33   - base.send( :extend, ClassMethods )
  33 + base.send( :extend, ActsMethods )
34 34 end
35 35
36   - module ClassMethods #:nodoc:
  36 + module ActsMethods #:nodoc:
37 37
38 38 # A model that needs to be tableless will call this method to indicate
39 39 # it.
@@ -47,6 +47,7 @@ def has_no_table
47 47
48 48 # extend
49 49 extend ActiveRecord::Tableless::SingletonMethods
  50 + extend ActiveRecord::Tableless::ClassMethods
50 51
51 52 # include
52 53 include ActiveRecord::Tableless::InstanceMethods
@@ -80,8 +81,32 @@ def #{m}
80 81
81 82 end
82 83
  84 + module ClassMethods
  85 +
  86 + def from_query_string(query_string)
  87 + unless query_string.blank?
  88 + params = query_string.split('&').collect do |chunk|
  89 + next if chunk.empty?
  90 + key, value = chunk.split('=', 2)
  91 + next if key.empty?
  92 + value = value.nil? ? nil : CGI.unescape(value)
  93 + [ CGI.unescape(key), value ]
  94 + end.compact.to_h
  95 +
  96 + new(params)
  97 + else
  98 + new
  99 + end
  100 + end
  101 +
  102 + end
  103 +
83 104 module InstanceMethods
84 105
  106 + def to_query_string(prefix = nil)
  107 + attributes.to_a.collect{|(name,value)| escaped_var_name(name, prefix) + "=" + escape_for_url(value) if value }.compact.join("&")
  108 + end
  109 +
85 110 %w(save destroy).each do |m|
86 111 eval %{
87 112 def #{m}
@@ -91,6 +116,23 @@ def #{m}
91 116 }
92 117 end
93 118
  119 + private
  120 +
  121 + def escaped_var_name(name, prefix = nil)
  122 + prefix ? "#{URI.escape(prefix)}[#{URI.escape(name)}]" : URI.escape(name)
  123 + end
  124 +
  125 + def escape_for_url(value)
  126 + case value
  127 + when true then "1"
  128 + when false then "0"
  129 + when nil then ""
  130 + else URI.escape(value.to_s)
  131 + end
  132 + rescue
  133 + ""
  134 + end
  135 +
94 136 end
95 137
96 138 end

0 comments on commit 3222a7a

Please sign in to comment.
Something went wrong with that request. Please try again.