simple_mysql_api 0.0.3 → 0.0.4

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore CHANGED
@@ -15,3 +15,4 @@ spec/reports
15
15
  test/tmp
16
16
  test/version_tmp
17
17
  tmp
18
+ .DS_Store
@@ -1,7 +1,12 @@
1
- # require File.join(File.expand_path(File.dirname(__FILE__)), 'simple_mysql_api/version')
2
- # require File.join(File.expand_path(File.dirname(__FILE__)), 'simple_mysql_api/class_methods')
3
1
  require "simple_mysql_api/version"
4
- require "simple_mysql_api/class_methods"
2
+ require "simple_mysql_api/class_methods.rb"
5
3
  module SimpleMysqlApi
6
- # Your code goes here...
4
+
5
+ # def self.connection_adapter
6
+ # /mysql|pg/.match(ActiveRecord::Base.configurations[Rails.env]['adapter'].downcase).to_s
7
+ # end
8
+ #
9
+ # # Add the class methods to the models
10
+ # ActiveRecord::Base.send(:include, MySqlMethods) if SimpleMysqlApi.connection_adapter=="mysql"
11
+ # ActiveRecord::Base.send(:include, PgMethods) if SimpleMysqlApi.connection_adapter=="pg"
7
12
  end
@@ -1,95 +1,174 @@
1
1
  module SimpleMysqlApi
2
+
3
+ #To add the class methods to Models
2
4
  module SimpleMysqlApiMethods
5
+
6
+ #Class methods for modles
3
7
  module ClassMethods
4
- def all_belongs_to_tables
5
- self.reflect_on_all_associations(:belongs_to).inject({}) do |r, e|
8
+
9
+ # Returns the asscociated models with their table name, class name, forignkey
10
+ # eg. User.tables_by_relation(:has_many)
11
+ # returns {"City"=>{:t_name=>"cities", :f_key=>"user_id"}}
12
+ def tables_by_relation(rel)
13
+ self.reflect_on_all_associations(rel).inject({}) do |r, e|
6
14
  r[e.class_name] = {:t_name=> e.table_name, :f_key=> e.foreign_key }
7
15
  r
8
16
  end
9
17
  end
10
-
11
- def attributes
12
- self.columns.inject({}) do |r,e|
13
- r[e.name.to_sym]= e.type.to_s
18
+
19
+ # Returns the hash of attributes of the table and their type
20
+ # eg. User.attributes
21
+ # returns [{:attr=>"id", :type=>"integer", :param_name=>:id}, {:attr=>"name", :type=>"string", :param_name=>:name}]
22
+ def attributes(c_name=nil)
23
+ self.columns.inject([]) do |r,e|
24
+ r << {:attr=>e.name, :type=>e.type.to_s, :param_name => (c_name ? (c_name.downcase+ "_" + e.name) : e.name).to_sym }
14
25
  r
15
26
  end
16
27
  end
17
-
28
+
29
+ # Returns the primary key
18
30
  def pri_key
19
31
  self.primary_key
20
32
  end
21
33
 
22
- def searchable_attributes
23
- self.attributes.delete_if{|k,v| (self.primary_key==k.to_s || self.foreign_keys.include?(k.to_s)) }
34
+ # returns all the attributes except primary keys and foreign keys
35
+ def searchable_attributes(c_name=nil)
36
+ self.attributes(c_name).delete_if{|v| (self.primary_key==v[:attr].to_s || self.foreign_keys.include?(v[:attr].to_s)) }
24
37
  end
25
-
38
+
39
+ # Adds the conditions for the attributes passed based on the attributes type
26
40
  def search_conditions(attributes,params,act_relation,t_type)
27
- attributes.each do |attr, value|
28
- case(value)
41
+ attributes.each do |value|
42
+ case(value[:type])
29
43
  when "string","text"
30
- act_relation = text_search(attr,params,act_relation,t_type) if params[attr]
44
+ act_relation = text_search(value,params,act_relation,t_type)
31
45
  when "integer","float"
32
- act_relation = range_search(attr,params,act_relation,t_type) if params[attr]
46
+ act_relation = range_search(value,params,act_relation,t_type)
47
+ when "datetime"
48
+ act_relation = date_search(value,params,act_relation,t_type)
33
49
  when "boolean"
34
- act_relation = boolean_search(attr,params,act_relation,t_type) if params[attr]
35
- end
50
+ act_relation = boolean_search(value,params,act_relation,t_type)
51
+ end if params[value[:param_name]]
36
52
  end
37
53
  act_relation
38
54
  end
39
-
55
+
56
+ # for the text search if it contains the string
40
57
  def text_search(attr,params,act_relation,t_type)
41
- obj = "%#{params[attr]}%"
42
- act_relation.where(["LOWER(#{t_type.constantize.table_name}.#{attr}) like LOWER(?)",obj])
58
+ obj = "%#{params[attr[:param_name]].downcase}%"
59
+ act_relation.where(["LOWER(#{t_type.constantize.table_name}.#{attr[:attr]}) like ?",obj])
43
60
  end
44
-
61
+
62
+ # for the integer, float attributes
63
+ # eg. price="12"
64
+ # price="12-100"
65
+ # price="<100"
66
+ # price=">100"
45
67
  def range_search(attr,params,act_relation,t_type)
46
- attr_opp = /[-,<,>]/.match(params[attr]).to_s
47
- table_name = "#{t_type.constantize.table_name}"
68
+ attr_opp = /[-,<,>]/.match(params[attr[:param_name]]).to_s + /[=]/.match(params[attr[:param_name]]).to_s
69
+ table_name = "#{t_type.constantize.table_name}"
48
70
  case(attr_opp)
49
71
  when "-"
50
- attr_val = params[attr].split("-").inject([]){|r,e| r << e.to_f}
51
- act_relation = act_relation.where(["CAST(#{table_name}.#{attr} AS DECIMAL) >= ? and CAST(#{table_name}.#{attr} AS DECIMAL) <= ?",attr_val[0],attr_val[1]]) if attr_val
52
- when "<",">"
53
- attr_val = params[attr].split(attr_opp)[1].to_f
54
- act_relation = act_relation.where([" CAST(#{table_name}.#{attr} AS DECIMAL) #{attr_opp} ?",attr_val]) if attr_val
72
+ attr_val = params[attr[:param_name]].split("-").inject([]){|r,e| r << e.to_f}
73
+ act_relation = act_relation.where(["CAST(#{table_name}.#{attr[:attr]} AS DECIMAL) >= ? and CAST(#{table_name}.#{attr[:attr]} AS DECIMAL) <= ?",attr_val[0],attr_val[1]]) if attr_val
74
+ when "<",">","<=",">="
75
+ attr_val = params[attr[:param_name]].split(attr_opp)[1].to_f
76
+ act_relation = act_relation.where(["CAST(#{table_name}.#{attr[:attr]} AS DECIMAL) #{attr_opp} ?",attr_val]) if attr_val
55
77
  else
56
- attr_val = params[attr].to_f
57
- act_relation = act_relation.where(["CAST(#{table_name}.#{attr} AS DECIMAL) = ?",attr_val]) if attr_val
78
+ attr_val = params[attr[:param_name]].to_f
79
+ act_relation = act_relation.where(["CAST(#{table_name}.#{attr[:attr]} AS DECIMAL) = ?",attr_val]) if attr_val
80
+ end if attr_opp
81
+ act_relation
82
+ end
83
+
84
+ # for the datetime
85
+ # eg. created_at ="2012-08-28 16:21:37 +0530"
86
+ # created_at = "2012-08-28 16:21:37 +0530..2012-09-28 16:21:37 +0530""
87
+ # created_at="<2012-08-28 16:21:37 +0530"
88
+ # created_at=">2012-08-28 16:21:37 +0530"
89
+ def date_search(attr,params,act_relation,t_type)
90
+ attr_opp = /[<,>]/.match(params[attr[:param_name]]).to_s + /[=]/.match(params[attr[:param_name]]).to_s
91
+ attr_opp = params[attr[:param_name]].index("..") ? ".." : attr_opp
92
+ table_name = "#{t_type.constantize.table_name}"
93
+ case(attr_opp)
94
+ when ".."
95
+ attr_val = params[attr[:param_name]].split("..").inject([]){|r,e| r << e}
96
+ act_relation = act_relation.where(["#{table_name}.#{attr[:attr]} >= ? and #{table_name}.#{attr[:attr]} <= ?",attr_val[0],attr_val[1]]) if attr_val
97
+ when "<",">","<=",">="
98
+ attr_val = params[attr[:param_name]].split(attr_opp)[1]
99
+ act_relation = act_relation.where(["#{table_name}.#{attr[:attr]} #{attr_opp} ?",attr_val]) if attr_val
100
+ else
101
+ attr_val = params[attr[:param_name]].split(attr_opp)[1]
102
+ act_relation = act_relation.where(["#{table_name}.#{attr[:attr]} = ?",attr_val]) if attr_val
58
103
  end if attr_opp
59
104
  act_relation
60
105
  end
61
106
 
107
+ # for any type
108
+ # eg. price="12"
62
109
  def equal_search(attr,params,act_relation,t_type)
63
- act_relation = act_relation.where(["#{t_type.constantize.table_name}.#{attr} = ?",params[attr]])
110
+ act_relation = act_relation.where(["#{t_type.constantize.table_name}.#{attr[:attr]} = ?",params[attr[:param_name]]])
64
111
  end
65
-
112
+
113
+ # for boolean type
114
+ # eg. price="true"
66
115
  def boolean_search(attr,params,act_relation,t_type)
67
- val = params[attr].match(/(true|t|yes|y|1)$/i) != nil ? 1 : 0
68
- act_relation = act_relation.where(["CAST(#{t_type.constantize.table_name}.#{attr} AS CHAR) = ?",val.to_s])
116
+ val = params[attr[:param_name]].match(/(true|t|yes|y|1)$/i) != nil ? 1 : 0
117
+ act_relation = act_relation.where(["CAST(#{t_type.constantize.table_name}.#{attr[:attr]} AS CHAR) = ?",val.to_s])
69
118
  end
70
-
119
+
120
+ # Returns all foreign keys of the model
71
121
  def foreign_keys
72
122
  self.reflect_on_all_associations.inject([]) do |r, e|
73
123
  r << e.foreign_key
74
124
  r
75
- end
125
+ end.uniq
76
126
  end
77
-
78
- def search(params,search_params=nil)
127
+
128
+ # Main method:
129
+ # Used for search
130
+ # You have params= {name: "Joh", city: "New"}
131
+ # set has_many, belongs_to to true if you want to search for associated models
132
+ # Search: User.search({search_params: params, has_many: true, belongs_to: false})
133
+ def mysql_search(options={})
134
+ params = options[:search_params]
135
+ search_params = options[:custom_params] || nil
79
136
  act_relation = self
80
- attributes = (search_params||self.attributes).delete_if{|k,v| ((self.foreign_keys.include? k.to_s)||self.primary_key==k.to_s) }
81
- self.all_belongs_to_tables.each do |c_name,values|
137
+ attributes = (search_params||self.attributes).delete_if{|v| (self.primary_key==v[:attr].to_s || self.foreign_keys.include?(v[:attr].to_s)) }
138
+ act_relation = belongs_to_search(act_relation, params) if options[:belongs_to] && options[:belongs_to]==true
139
+ act_relation = has_many_search(act_relation, params) if options[:has_many] && options[:has_many]==true
140
+ act_relation = search_conditions(attributes,params,act_relation,self.to_s)
141
+ act_relation.select("DISTINCT #{self.table_name}.*")
142
+ end
143
+
144
+ # For joining belongs to relational models and searches their params
145
+ def belongs_to_search(act_relation, params)
146
+ self.tables_by_relation(:belongs_to).each do |c_name,values|
82
147
  act_relation = act_relation.joins("LEFT JOIN #{values[:t_name]} #{values[:t_name]} ON #{self.table_name}.#{values[:f_key]}=#{values[:t_name]}.#{c_name.constantize.pri_key}")
83
- new_attributes = c_name.constantize.searchable_attributes
148
+ new_attributes = c_name.constantize.searchable_attributes(c_name)#c_name.constantize.searchable_attributes
84
149
  act_relation = search_conditions(new_attributes,params,act_relation,c_name)
85
150
  end
86
- act_relation = search_conditions(attributes,params,act_relation,self.to_s)
87
151
  act_relation
88
152
  end
153
+
154
+ # For joining has many relational models and searches their params
155
+ def has_many_search(act_relation, params)
156
+ self.tables_by_relation(:has_many).each do |c_name,values|
157
+ act_relation = act_relation.joins("LEFT JOIN #{values[:t_name]} #{values[:t_name]} ON #{self.table_name}.#{self.pri_key}=#{values[:t_name]}.#{values[:f_key]}")
158
+ new_attributes = c_name.constantize.searchable_attributes(c_name)#c_name.constantize.searchable_attributes
159
+ act_relation = search_conditions(new_attributes,params,act_relation,c_name)
160
+ end
161
+ act_relation
162
+ end
163
+
89
164
  end
165
+
166
+ # includes as class methods for the Class
90
167
  def self.included(base)
91
168
  base.extend ClassMethods
92
169
  end
93
170
  end
171
+
172
+ # Add the class methods to the models
94
173
  ActiveRecord::Base.send(:include, SimpleMysqlApiMethods)
95
174
  end
@@ -1,3 +1,3 @@
1
1
  module SimpleMysqlApi
2
- VERSION = "0.0.3"
2
+ VERSION = "0.0.4"
3
3
  end
@@ -5,11 +5,13 @@ require 'simple_mysql_api/version'
5
5
  Gem::Specification.new do |gem|
6
6
  gem.name = "simple_mysql_api"
7
7
  gem.version = SimpleMysqlApi::VERSION
8
- gem.authors = ["jalendrabhanarkar"]
9
- gem.email = ["jalendra@sapnasolutions.com"]
10
- gem.description = "Used for basic api operations,like searching etc."
11
- gem.summary = "First gem to check the functionality."
12
- gem.homepage = ""
8
+ gem.authors = ["Jalendra Bhanarkar"]
9
+ gem.email = ["jbmyid@gmail.com"]
10
+ gem.description = "Search the records by attributes of the same table or associated tables. Search: Ex. User.search({search_params: {name: \"Alex\", city: \"New\"}, belongs_to: false, has_many: true}) will return the User active relation with conditioning name=Alex and city=new"
11
+ gem.summary = "Search the records by attributes of the same table or associated tables."
12
+ gem.homepage = "http://jbmyid.wordpress.com"
13
+ gem.add_dependency('rails', '>= 3.2')
14
+ # gem.add_dependency('ActiveRecord','>= 3.2')
13
15
 
14
16
  gem.files = `git ls-files`.split($/)
15
17
  gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
metadata CHANGED
@@ -1,19 +1,33 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: simple_mysql_api
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.3
4
+ version: 0.0.4
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
8
- - jalendrabhanarkar
8
+ - Jalendra Bhanarkar
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2012-09-04 00:00:00.000000000 Z
13
- dependencies: []
14
- description: Used for basic api operations,like searching etc.
12
+ date: 2012-09-10 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rails
16
+ requirement: &2151943920 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '3.2'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: *2151943920
25
+ description: ! 'Search the records by attributes of the same table or associated tables.
26
+ Search: Ex. User.search({search_params: {name: "Alex", city: "New"}, belongs_to:
27
+ false, has_many: true}) will return the User active relation with conditioning name=Alex
28
+ and city=new'
15
29
  email:
16
- - jalendra@sapnasolutions.com
30
+ - jbmyid@gmail.com
17
31
  executables: []
18
32
  extensions: []
19
33
  extra_rdoc_files: []
@@ -28,7 +42,7 @@ files:
28
42
  - lib/simple_mysql_api/class_methods.rb
29
43
  - lib/simple_mysql_api/version.rb
30
44
  - simple_mysql_api.gemspec
31
- homepage: ''
45
+ homepage: http://jbmyid.wordpress.com
32
46
  licenses: []
33
47
  post_install_message:
34
48
  rdoc_options: []
@@ -51,5 +65,5 @@ rubyforge_project:
51
65
  rubygems_version: 1.8.15
52
66
  signing_key:
53
67
  specification_version: 3
54
- summary: First gem to check the functionality.
68
+ summary: Search the records by attributes of the same table or associated tables.
55
69
  test_files: []