pretty_association_inspect 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 2cf4a0aa15d29d6596bb7c227aff74cd0665f2a1
4
+ data.tar.gz: e754a3b84739cd215cd787c0abf7047783d717b9
5
+ SHA512:
6
+ metadata.gz: b3b2ec246f63152898062d5149d7bdbbf3ef1a668e014af135b0333c1c86c4bea7056029f1f25e6f45e5a28301476dd9a352d80e65b7cdfb21cbda1cdfff4a1e
7
+ data.tar.gz: 4ae7644a1a2790f16c5cebede36a1237a186546ee5cf5a7e4ead9dd019924b2c3aa81a754a956e10aac47260bb10c98d3e7d2912ced7d886555e0e3bc52f90a2
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.1
4
+ before_install: gem install bundler -v 1.10.5
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in pretty_association_inspect.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 TODO: Write your name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # PrettyAssociationInspect
2
+ モデルで定義されたメソッド、関連、バリデーションを
3
+ コンソール上で美しく表示します。
4
+
5
+ ## Installation
6
+
7
+ ```ruby
8
+ gem 'pretty_association_inspect'
9
+ ```
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install pretty_association_inspect
18
+
19
+ ## Usage
20
+
21
+ ### メソッド、関連、バリデーションを表示する
22
+
23
+ ```rb
24
+ User.to
25
+ ```
26
+
27
+ ### 関連を、4モデル先まで表示する(デフォルトは1モデル先)
28
+
29
+ ```rb
30
+ User.toto 4
31
+ ```
32
+
33
+ ### カラムのカラムの部分一致検索
34
+
35
+ ```rb
36
+ User.s "小野寺"
37
+ ```
38
+
39
+ ### カラムのカラムの完全一致検索
40
+
41
+ ```rb
42
+ User.ss "小野寺"
43
+ ```
44
+
45
+ ## License
46
+
47
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "pretty_association_inspect"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,3 @@
1
+ module PrettyAssociationInspect
2
+ VERSION = "1.0.1"
3
+ end
@@ -0,0 +1,247 @@
1
+ # -*- coding: utf-8 -*-
2
+ # モデルに関連情報を見やすく表示するメソッドを定義します。
3
+ module PrettyAssociationInspect
4
+ extend self
5
+
6
+ class Edge
7
+ def initialize(cost, node_id)
8
+ @cost, @node_id = cost, node_id
9
+ end
10
+ attr_reader :cost, :node_id
11
+ end
12
+
13
+ class Node
14
+ def initialize(id, edges, cost=nil, done=false, from=nil)
15
+ @id, @edges, @cost, @done, @from = id, edges, cost, done, from
16
+ end
17
+ attr_accessor :id, :edges, :cost, :done, :from
18
+ end
19
+
20
+ class Graph
21
+ def initialize(data)
22
+ @nodes = data.map do |node_id, edges|
23
+ edges.map!{|edge| Edge.new(*edge)}
24
+ Node.new(node_id, edges)
25
+ end
26
+ end
27
+
28
+ def print_route(route)
29
+ return false if route[0].cost.nil?
30
+ route_arr = route.map{|node| node.id}
31
+ start_name = route_arr.pop.to_s.camelize
32
+ route_arr.reverse!
33
+ h = Hash.new
34
+ h[route_arr.first] = {} if route_arr.count == 1
35
+ h[route_arr.first] = route_arr.second if route_arr.count == 2
36
+ h[route_arr.first] = {route_arr.second => route_arr.third} if route_arr.count == 3
37
+ h[route_arr.first] = {route_arr.second => {route_arr.third => route_arr.fourth}} if route_arr.count == 4
38
+ route_str = "#{start_name}.joins(#{h.to_s}).last." + route_arr.join(".").gsub("s.", "s.last.")
39
+ ap route_str
40
+ return route_str
41
+ end
42
+
43
+ def minimum_route(start_id, goal_id, max_cost)
44
+ search_by_dikstra(start_id, goal_id, max_cost)
45
+ passage = @nodes.find { |node| node.id == goal_id }
46
+ route = [passage]
47
+ while passage = @nodes.find { |node| node.id == passage.from }
48
+ route << passage
49
+ end
50
+ route
51
+ end
52
+
53
+ def search_by_dikstra(start_id, goal_id, max_cost)
54
+ @nodes.each do |node|
55
+ node.cost = node.id == start_id ? 0 : nil
56
+ node.done = false
57
+ node.from = nil
58
+ end
59
+ loop do
60
+ next_node = nil
61
+ @nodes.each do |node|
62
+ next if node.done || node.cost.nil?
63
+ next_node = node if next_node.nil? || node.cost < next_node.cost
64
+ end
65
+ break if next_node.nil?
66
+ next_node.done = true
67
+ next_node.edges.each do |edge|
68
+ reachble_node = @nodes.find { |node| node.id == edge.node_id }
69
+ reachble_cost = next_node.cost + edge.cost
70
+ next if reachble_node.nil?
71
+ next if reachble_cost > max_cost
72
+ if reachble_node.cost.nil? || reachble_cost < reachble_node.cost
73
+ reachble_node.cost = reachble_cost
74
+ reachble_node.from = next_node.id
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
80
+
81
+ def build_association_node(start, max_cost)
82
+ models = ActiveRecord::Base.subclasses.map(&:name)
83
+ data = models.each_with_object({}) do |model_name_str, hash|
84
+ eval(model_name_str).reflect_on_all_associations.each do |m|
85
+ model_single_name = eval(model_name_str).model_name.singular.to_sym
86
+ model_multiple_name = eval(model_name_str).model_name.plural.to_sym
87
+ hash[model_single_name] ||= []
88
+ hash[model_multiple_name] ||= []
89
+ hash[model_single_name] << [1, m.name]
90
+ hash[model_multiple_name] << [1, m.name]
91
+ end
92
+ end
93
+ graph = Graph.new(data)
94
+ route_hash = {}
95
+ data.each do |goal, v|
96
+ next if start == goal
97
+ new_route = graph.print_route(graph.minimum_route(start, goal, max_cost))
98
+ _model_ = ActiveRecord::Base.module_eval(goal.to_s.camelize.singularize).model_name.human rescue nil
99
+ human_str = PrettyAssociationInspect.jp_scripe(_model_)
100
+ route_hash["#{goal} #{human_str}"] = new_route if new_route
101
+ end
102
+ route_hash
103
+ end
104
+
105
+
106
+ # 『関連を可愛く表示するメソッド』を定義する
107
+ def pretty_association_inspect_define(klass)
108
+ klass.class_eval do |model|
109
+ self.define_singleton_method(:to){
110
+ associations_hash = PrettyAssociationInspect.build_association_hash(model)
111
+ PrettyAssociationInspect.printed(klass, model, associations_hash)
112
+ return self.first || self
113
+ }
114
+
115
+ define_method(:to){
116
+ associations_hash = PrettyAssociationInspect.build_association_hash(model)
117
+ PrettyAssociationInspect.printed(klass, model, associations_hash)
118
+ return self
119
+ }
120
+ self.define_singleton_method(:toto){ |max_cost=1, start = nil|
121
+ model_name_sym = model_name.singular.to_sym
122
+ route_arr = PrettyAssociationInspect.build_association_node(start || model_name_sym, max_cost)
123
+ ap route_arr.map { |route| [route.first, eval(route.last.to_s)] rescue nil }
124
+ ap route_arr
125
+ return nil
126
+ }
127
+ define_method(:toto){ |max_cost = 1, start = nil|
128
+ model_name_sym = model_name.singular.to_sym
129
+ route_arr = PrettyAssociationInspect.build_association_node(start || model_name_sym, max_cost)
130
+ ap route_arr.map { |route| [route.first, eval(route.last.to_s)] rescue nil }
131
+ ap route_arr
132
+ return nil
133
+ }
134
+ self.define_singleton_method(:s){ |name = nil|
135
+ results = Module.const_get(self.to_s).columns.select{|m| m.sql_type=~/char/}.map(&:name).map(&:to_sym).each_with_object([]) { |attr, records|
136
+ result = self.where(self.arel_table[attr].matches("%#{name}%"))
137
+ records << [attr, result.ids, result]
138
+ }.select{|m| m.second.present? }
139
+ ap results
140
+ result_where = self.where(id: results.map(&:second).flatten)
141
+ ap result_where
142
+ return result_where
143
+ }
144
+ end
145
+ end
146
+
147
+ # バリューを整形
148
+ def value_convert(k, v, klass)
149
+ klass.class_eval {
150
+ return columns_hash[k.to_s].type if v.blank?
151
+ is_e = Object.const_defined?(:Enumerize) && first.send(k).kind_of?(Enumerize::Value)
152
+ return "#{v} #{first.send(k).text} #{send(k).values} #{send(k).values.map(&:text)}" if is_e
153
+ return v.strftime("%y年%m月%d日 %H:%M") if v.respond_to?(:strftime)
154
+ }
155
+ end
156
+
157
+ # アソシエーションをハッシュに変換
158
+ def build_association_hash(model)
159
+ pretty_hash = model.reflect_on_all_associations.each_with_object({}) do |m, hash|
160
+ name = m.class.to_s.gsub("ActiveRecord::Reflection::", "").gsub("Reflection", "").to_sym
161
+ hash[name] ||= []
162
+ human_name = PrettyAssociationInspect.jp_scripe(m.klass.model_name.human)
163
+ hash[name] << [
164
+ m.name, human_name
165
+ ].compact.join(' | ')
166
+ hash[name] = hash[name]
167
+ end
168
+ end
169
+
170
+ # 表示
171
+ def printed(klass, model, associations_hash)
172
+ pretty_hash = {}
173
+ begin
174
+ klass.class_eval{|klass|
175
+ klass.first.attributes.each{|k ,v|
176
+ pretty_hash[k.to_sym] =
177
+ [
178
+ PrettyAssociationInspect.value_convert(k, v, klass),
179
+ PrettyAssociationInspect.jp_scripe(klass.human_attribute_name(k)),
180
+ v
181
+ ].compact.join(' | ')
182
+ }
183
+ }
184
+ rescue => e
185
+ ap e
186
+ end
187
+ ap "-"*100;
188
+ ap "#{klass.name} #{jp_scripe(klass.model_name.human)}"
189
+ ap "[クラスメソッド]"
190
+ base_pattern = "(before|after|around)_(add|remove|restore)|_associated_records_for_|inherited"
191
+ extr_pattern = "attribute_type_decorations|soft_de|_restore_callback|indexed_|_by_resource"
192
+ delete_pattern = Regexp.new( [ base_pattern, extr_pattern ].join('|') )
193
+ class_m = model.methods(false) - model.instance_methods
194
+ ap (class_m).delete_if{|name|
195
+ delete_pattern.match(name) }.sort
196
+ ap "[インスタンスメソッド]"
197
+ instance_m = model.instance_methods(false) - model.superclass.instance_methods
198
+ ap (instance_m).delete_if{|name|
199
+ delete_pattern.match(name) }.sort
200
+ ap "[バリデーション]"
201
+ ap model.validators.map{|m|
202
+ m.class.name.gsub(/Active|Record|Validations|Model|Validator|::/,"")
203
+ .concat(" #{m.attributes.join(', ')} #{m.options}") }.sort.uniq
204
+ ap "[アソシエーション]"
205
+ ap associations_hash
206
+ ap "[詳細]"
207
+ ap pretty_hash
208
+ ap "-"*100
209
+ end
210
+
211
+ # 日本語だけ抽出
212
+ def jp_scripe(str)
213
+ japanese = Regexp.new(/[亜-熙ぁ-んァ-ヶ]/)
214
+ str if japanese =~ str
215
+ end
216
+
217
+ # 全てのモデルにメソッドを定義する
218
+ def all_models_define
219
+ model_names_array = load_all_models
220
+ model_names_array.each do |model_name|
221
+ begin
222
+ klass = eval(model_name)
223
+ pretty_association_inspect_define(klass)
224
+ rescue
225
+ next
226
+ end
227
+ end
228
+ end
229
+
230
+ # 全てのモデルを読み込み、モデル名配列を返す
231
+ def load_all_models
232
+ models_file_path = Dir.glob(Rails.root.join("app/models/*")).grep(/rb\z/)
233
+ models_file_path.each { |m| require(m) rescue next }
234
+ return ActiveRecord::Base.subclasses.map(&:name)
235
+ end
236
+
237
+ end
238
+ module Kernel
239
+ extend self
240
+ define_method(:ss) {|keyword = nil|
241
+ ActiveRecord::Base.connection.tables.map(&:classify).map{|m| Object.const_get(m) rescue nil}.each_with_object({}){|m,h| h[m.try(:name).try(:to_sym)] = m.try(:column_names)}.compact.select{|_,v| v.any?{|m| keyword.nil? ? true : m.match(keyword) }}
242
+ }
243
+ define_method(:sss) {|keyword = nil|
244
+ result = ActiveRecord::Base.connection.tables.map(&:classify).map{|m| Object.const_get(m) rescue nil}.each_with_object({}){|m,h| h[m.try(:name).try(:to_sym)] = m.try(:column_names)}.compact.select{|_,v| v.any?{|m| keyword.nil? ? true : m == keyword }}
245
+ result.keys
246
+ }
247
+ end
@@ -0,0 +1,29 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'pretty_association_inspect/version'
5
+
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "pretty_association_inspect"
9
+ spec.version = PrettyAssociationInspect::VERSION
10
+ spec.authors = ["小野寺 優太"]
11
+ spec.email = ["s1160054@gmail.com"]
12
+
13
+ spec.summary = %q{モデルで定義されたメソッド、関連、バリデーションを、Railsコンソール上で美しく表示します。}
14
+ spec.description = %q{すべてのモデルに「to」というクラスメソッド及びインスタンスメソッドが追加されます。}
15
+ spec.homepage = "https://github.com/s1160054/pretty_association_inspect.git"
16
+ spec.license = "MIT"
17
+
18
+ #Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
19
+ #delete this section to allow pushing this gem to any host.
20
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
+ spec.bindir = "exe"
22
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
23
+ spec.require_paths = ["lib"]
24
+
25
+ spec.add_development_dependency "bundler"
26
+ spec.add_development_dependency "rake"
27
+ spec.add_development_dependency "rails"
28
+ spec.add_development_dependency "awesome_print"
29
+ end
metadata ADDED
@@ -0,0 +1,112 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pretty_association_inspect
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.1
5
+ platform: ruby
6
+ authors:
7
+ - "小野寺 優太"
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-09-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rails
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: awesome_print
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: "すべてのモデルに「to」というクラスメソッド及びインスタンスメソッドが追加されます。"
70
+ email:
71
+ - s1160054@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".travis.yml"
78
+ - CODE_OF_CONDUCT.md
79
+ - Gemfile
80
+ - LICENSE.txt
81
+ - README.md
82
+ - Rakefile
83
+ - bin/console
84
+ - bin/setup
85
+ - lib/pretty_association_inspect.rb
86
+ - lib/pretty_association_inspect/version.rb
87
+ - pretty_association_inspect.gemspec
88
+ homepage: https://github.com/s1160054/pretty_association_inspect.git
89
+ licenses:
90
+ - MIT
91
+ metadata: {}
92
+ post_install_message:
93
+ rdoc_options: []
94
+ require_paths:
95
+ - lib
96
+ required_ruby_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ required_rubygems_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ requirements: []
107
+ rubyforge_project:
108
+ rubygems_version: 2.4.5.1
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: "モデルで定義されたメソッド、関連、バリデーションを、Railsコンソール上で美しく表示します。"
112
+ test_files: []