rails_polymorphic_select 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (65) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +86 -0
  4. data/Rakefile +21 -0
  5. data/lib/rails_polymorphic_select.rb +6 -0
  6. data/lib/rails_polymorphic_select/belongs_to_builder_extension.rb +25 -0
  7. data/lib/rails_polymorphic_select/engine.rb +16 -0
  8. data/lib/rails_polymorphic_select/form_builder.rb +36 -0
  9. data/lib/rails_polymorphic_select/version.rb +3 -0
  10. data/spec/belongs_to_builder_extension_spec.rb +46 -0
  11. data/spec/dummy/README.rdoc +28 -0
  12. data/spec/dummy/Rakefile +6 -0
  13. data/spec/dummy/app/assets/javascripts/application.js +13 -0
  14. data/spec/dummy/app/assets/stylesheets/application.css +15 -0
  15. data/spec/dummy/app/controllers/application_controller.rb +5 -0
  16. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  17. data/spec/dummy/app/models/animal.rb +5 -0
  18. data/spec/dummy/app/models/planet.rb +5 -0
  19. data/spec/dummy/app/models/plant.rb +3 -0
  20. data/spec/dummy/app/models/star.rb +3 -0
  21. data/spec/dummy/app/views/layouts/application.html.erb +14 -0
  22. data/spec/dummy/bin/bundle +3 -0
  23. data/spec/dummy/bin/rails +4 -0
  24. data/spec/dummy/bin/rake +4 -0
  25. data/spec/dummy/bin/setup +29 -0
  26. data/spec/dummy/config.ru +4 -0
  27. data/spec/dummy/config/application.rb +32 -0
  28. data/spec/dummy/config/boot.rb +5 -0
  29. data/spec/dummy/config/database.yml +25 -0
  30. data/spec/dummy/config/environment.rb +5 -0
  31. data/spec/dummy/config/environments/development.rb +41 -0
  32. data/spec/dummy/config/environments/production.rb +79 -0
  33. data/spec/dummy/config/environments/test.rb +42 -0
  34. data/spec/dummy/config/initializers/assets.rb +11 -0
  35. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  36. data/spec/dummy/config/initializers/cookies_serializer.rb +3 -0
  37. data/spec/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  38. data/spec/dummy/config/initializers/inflections.rb +16 -0
  39. data/spec/dummy/config/initializers/mime_types.rb +4 -0
  40. data/spec/dummy/config/initializers/session_store.rb +3 -0
  41. data/spec/dummy/config/initializers/wrap_parameters.rb +14 -0
  42. data/spec/dummy/config/locales/en.yml +23 -0
  43. data/spec/dummy/config/routes.rb +56 -0
  44. data/spec/dummy/config/secrets.yml +22 -0
  45. data/spec/dummy/db/development.sqlite3 +0 -0
  46. data/spec/dummy/db/migrate/20150911212009_create_animals.rb +12 -0
  47. data/spec/dummy/db/migrate/20150911212401_create_plants.rb +10 -0
  48. data/spec/dummy/db/migrate/20150912014900_create_stars.rb +8 -0
  49. data/spec/dummy/db/migrate/20150912015008_create_planets.rb +9 -0
  50. data/spec/dummy/db/schema.rb +45 -0
  51. data/spec/dummy/db/test.sqlite3 +0 -0
  52. data/spec/dummy/log/development.log +251 -0
  53. data/spec/dummy/log/test.log +1364 -0
  54. data/spec/dummy/public/404.html +67 -0
  55. data/spec/dummy/public/422.html +67 -0
  56. data/spec/dummy/public/500.html +66 -0
  57. data/spec/dummy/public/favicon.ico +0 -0
  58. data/spec/factories/animals.rb +6 -0
  59. data/spec/factories/planets.rb +6 -0
  60. data/spec/factories/plants.rb +6 -0
  61. data/spec/factories/stars.rb +5 -0
  62. data/spec/form_builder_spec.rb +78 -0
  63. data/spec/rails_helper.rb +58 -0
  64. data/spec/spec_helper.rb +93 -0
  65. metadata +255 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 28c824dd9b61280b7557b2f27b86af716ce12970
4
+ data.tar.gz: b774ca1261b1c6da982faee850c52fdacbd26ae8
5
+ SHA512:
6
+ metadata.gz: 8ff560f243aa824ccca4b186ef9c1dddf505360437abecb477593b48d0e443e799aafb05ffe561f9bd8a114b5e920e0ca5265ddeff6674ed8cd4f9a092799380
7
+ data.tar.gz: b45832487ed8ec86038280800578539b0257c15368b6ab41b1379b63c939670101907980d17d4cb87e996b24395258e6a56767f026089ce1c0f4bd4085735def
@@ -0,0 +1,20 @@
1
+ Copyright 2015 Brian Landau (Viget Labs)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,86 @@
1
+ # Rails Polymorphic Select
2
+
3
+ [![Build Status](https://travis-ci.org/vigetlabs/rails_polymorphic_select.png?branch=master)](https://travis-ci.org/vigetlabs/rails_polymorphic_select) [![Code Climate](https://codeclimate.com/github/vigetlabs/rails_polymorphic_select.png)](https://codeclimate.com/github/vigetlabs/rails_polymorphic_select)
4
+
5
+ This is a simple Rails extension that allows you to create polymorphic select inputs for relationships that are polymorphic.
6
+
7
+ ## Install
8
+
9
+ Just add this to your `Gemfile` and then `bundle install`:
10
+
11
+ ```ruby
12
+ gem 'rails_polymorphic_select'
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ When using any `ActionView::Helpers::FormBuilder` object (either from the `form_for` helper method or a custom `FormBuilder` object) you can now call the method `polymorphic_select` like so:
18
+
19
+ ```
20
+ <%= form.polymorphic_select :association_name_global_id, [News, Event, Photo] %>
21
+ ```
22
+
23
+ The first argument it accepts is a method name (like all `FormBuilder` input methods), except you'll notice it's a `*_global_id` method. This library will automatically add these methods on all polymorphic relationships you create in your app. So if I have a `Tagging` model and I have a polymorphic relationship named `taggable` like this:
24
+
25
+ ``ruby
26
+ class Tagging
27
+ belongs_to :tag
28
+ belongs_to :taggable, :polymorphic => true
29
+ end
30
+ ```
31
+
32
+ This will create a `taggable_global_id` method and a `taggable_global_id=` method for reading and setting the taggable item by it's Global ID. However, it will not add these methods for non-polymorphic relationships (like `tag` in this case). Rails added [`GlobalID`](https://github.com/rails/globalid) functionality in 4.2, so now all ActiveRecord models have a `to_global_id` method that will return a `GlobalID` object that can be used to find the record.
33
+
34
+ The second argument `polymorphic_select` takes is an `Array` of `ActiveRecord` model classes that are valid options for this polymorphic relationship.
35
+
36
+ The third argument is an `options` argument and this gets passed to the [`FormBuilder#select`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select). Before that however there's one extra option that `polymorphic_select` accepts: `:label_method`. This is used as the method to call on individual records to get the value that users would see on the form select input for each record. By default it tries to find a good method (name, title, to_s, etc). If you prefer you can define a `to_label` or `display_name` method on the model(s), and these will be used.
37
+
38
+ The fourth argument is a `html_options` argument and this gets passed directly unaltered to [`FormBuilder#select`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select).
39
+
40
+ Worth noting is this greats a grouped selct input. So the records will be grouped by model class. The `polymorphic_select` method will use `ModelClass.model_name.human` to label the group. You can modify the name it supplies by manually editing the i18n value for the model.
41
+
42
+
43
+ ### Advanced usage
44
+
45
+ Perhaps you have a `Tag` model with `taggings` but you want to access and set the individual `taggables`. In this case you could create your own `*_global_ids` methods and use this on with `polymorphic_select`. Say your `Tag` model looks like this:
46
+
47
+ ```ruby
48
+ class Tag
49
+ has_many :taggings
50
+
51
+ def taggables
52
+ taggings.map(&:taggable)
53
+ end
54
+
55
+ def taggable_global_ids
56
+ taggables.map(&:to_global_id)
57
+ end
58
+
59
+ def taggalbe_global_ids=(global_ids)
60
+ # your own code that at some point uses GlobalID::Locator.locate(global_id_value) to set the taggings
61
+ end
62
+ end
63
+ ```
64
+
65
+ Then in your form you could do:
66
+
67
+ ```
68
+ <%= form.polymorphic_select :taggable_global_ids, [News, Event, Photo] %>
69
+ ```
70
+
71
+ and it would just work!
72
+
73
+
74
+ ## Contributing to RailsPolymorphicSelect
75
+
76
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
77
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
78
+ * Fork the project.
79
+ * Start a feature/bugfix branch.
80
+ * Commit and push until you are happy with your contribution.
81
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
82
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
83
+
84
+ ## Copyright
85
+
86
+ Copyright (c) 2015 Brian Landau (Viget Labs). See MIT_LICENSE for further details.
@@ -0,0 +1,21 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__)
8
+ load 'rails/tasks/engine.rake'
9
+
10
+
11
+ load 'rails/tasks/statistics.rake'
12
+
13
+ Bundler::GemHelper.install_tasks
14
+
15
+ require 'rspec/core'
16
+ require 'rspec/core/rake_task'
17
+
18
+ desc "Run all specs in spec directory (excluding plugin specs)"
19
+ RSpec::Core::RakeTask.new(:spec => 'app:db:test:prepare')
20
+
21
+ task :default => :spec
@@ -0,0 +1,6 @@
1
+ require "rails_polymorphic_select/engine"
2
+
3
+ module RailsPolymorphicSelect
4
+ autoload :FormBuilder, 'rails_polymorphic_select/form_builder'
5
+ autoload :BelongsToBuilderExtension, 'rails_polymorphic_select/belongs_to_builder_extension'
6
+ end
@@ -0,0 +1,25 @@
1
+ module RailsPolymorphicSelect
2
+ module BelongsToBuilderExtension
3
+ def define_accessors(mixin, reflection)
4
+ super
5
+
6
+ if reflection.options[:polymorphic]
7
+ define_global_id_methods(mixin, reflection.name)
8
+ end
9
+ end
10
+
11
+ def define_global_id_methods(mixin, name)
12
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
13
+ def #{name}_global_id
14
+ #{name}.try(:to_global_id)
15
+ end
16
+
17
+ def #{name}_global_id=(new_global_id)
18
+ self.#{name} = if new_global_id.present?
19
+ GlobalID::Locator.locate(new_global_id)
20
+ end
21
+ end
22
+ CODE
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,16 @@
1
+ module RailsPolymorphicSelect
2
+ class Engine < ::Rails::Engine
3
+
4
+ config.generators do |g|
5
+ g.test_framework :rspec, :fixture => false
6
+ g.fixture_replacement :factory_girl, :dir => 'spec/factories'
7
+ g.assets false
8
+ g.helper false
9
+ end
10
+
11
+ initializer "rails_polymorphic_select.include_extensions" do |app|
12
+ ActionView::Helpers::FormBuilder.send(:include, RailsPolymorphicSelect::FormBuilder)
13
+ ActiveRecord::Associations::Builder::BelongsTo.extend RailsPolymorphicSelect::BelongsToBuilderExtension
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,36 @@
1
+ module RailsPolymorphicSelect
2
+ module FormBuilder
3
+ LABEL_NAME_METHODS = [
4
+ :to_label,
5
+ :display_name,
6
+ :label,
7
+ :name,
8
+ :title,
9
+ :username,
10
+ :login,
11
+ :value,
12
+ :to_s
13
+ ]
14
+
15
+ def polymorphic_select(method_name, models, options = {}, html_options = {})
16
+ label_method = options.delete(:label_method)
17
+
18
+ choices = models.map do |model_class|
19
+ [model_class.model_name.human, model_class.all.map { |record|
20
+ [label_for(record, label_method), record.to_global_id]
21
+ }]
22
+ end
23
+
24
+ select(method_name, choices, options, html_options)
25
+ end
26
+
27
+ private
28
+
29
+ def label_for(record, label_method)
30
+ unless label_method && record.respond_to?(label_method)
31
+ label_method = LABEL_NAME_METHODS.detect{|method_name| record.respond_to?(method_name) }
32
+ end
33
+ record.send(label_method)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,3 @@
1
+ module RailsPolymorphicSelect
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,46 @@
1
+ require 'rails_helper'
2
+
3
+ RSpec.describe RailsPolymorphicSelect::BelongsToBuilderExtension do
4
+ let(:zebra){ create(:animal, name: 'Zebra', scientific_name: 'Equus zebra') }
5
+ let(:cheetah){ create(:animal, eats: zebra)}
6
+
7
+ it 'creates a global id reader method for polymorphic belongs to relationships' do
8
+ expect(Animal.public_method_defined?(:eats_global_id)).to eql(true)
9
+ end
10
+
11
+ it 'creates a global id writer method for polymorphic belongs to relationships' do
12
+ expect(Animal.public_method_defined?(:eats_global_id=)).to eql(true)
13
+ end
14
+
15
+ it 'does not create a global id reader method for non-polymorphic belongs to relationships' do
16
+ expect(Planet.public_method_defined?(:star_global_id)).to eql(false)
17
+ end
18
+
19
+ it 'does not create a global id writer method for non-polymorphic belongs to relationships' do
20
+ expect(Planet.public_method_defined?(:star_global_id=)).to eql(false)
21
+ end
22
+
23
+ describe "#*_global_id" do
24
+ it "returns the related item's global id" do
25
+ expect(cheetah.eats_global_id).to eql(zebra.to_global_id)
26
+ end
27
+
28
+ it "returns nil if the relationship is not set" do
29
+ expect(zebra.eats_global_id).to be_nil
30
+ end
31
+ end
32
+
33
+ describe "#*_global_id=" do
34
+ it "relates the correct record" do
35
+ plant = create(:plant)
36
+ zebra.eats_global_id = plant.to_global_id
37
+ expect(zebra.eats).to eql(plant)
38
+ end
39
+
40
+ it "remove the relationship if the value is blank" do
41
+ cheetah.eats_global_id = ""
42
+ expect(cheetah.eats).to be_nil
43
+ end
44
+ end
45
+
46
+ end
@@ -0,0 +1,28 @@
1
+ == README
2
+
3
+ This README would normally document whatever steps are necessary to get the
4
+ application up and running.
5
+
6
+ Things you may want to cover:
7
+
8
+ * Ruby version
9
+
10
+ * System dependencies
11
+
12
+ * Configuration
13
+
14
+ * Database creation
15
+
16
+ * Database initialization
17
+
18
+ * How to run the test suite
19
+
20
+ * Services (job queues, cache servers, search engines, etc.)
21
+
22
+ * Deployment instructions
23
+
24
+ * ...
25
+
26
+
27
+ Please feel free to use a different markup language if you do not plan to run
28
+ <tt>rake doc:app</tt>.
@@ -0,0 +1,6 @@
1
+ # Add your own tasks in files placed in lib/tasks ending in .rake,
2
+ # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3
+
4
+ require File.expand_path('../config/application', __FILE__)
5
+
6
+ Rails.application.load_tasks
@@ -0,0 +1,13 @@
1
+ // This is a manifest file that'll be compiled into application.js, which will include all the files
2
+ // listed below.
3
+ //
4
+ // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5
+ // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6
+ //
7
+ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8
+ // compiled file.
9
+ //
10
+ // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
11
+ // about supported directives.
12
+ //
13
+ //= require_tree .
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any styles
10
+ * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
11
+ * file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,5 @@
1
+ class ApplicationController < ActionController::Base
2
+ # Prevent CSRF attacks by raising an exception.
3
+ # For APIs, you may want to use :null_session instead.
4
+ protect_from_forgery with: :exception
5
+ end
@@ -0,0 +1,2 @@
1
+ module ApplicationHelper
2
+ end
@@ -0,0 +1,5 @@
1
+ class Animal < ActiveRecord::Base
2
+ belongs_to :eats, polymorphic: true
3
+
4
+ validates :name, :scientific_name, presence: true
5
+ end
@@ -0,0 +1,5 @@
1
+ class Planet < ActiveRecord::Base
2
+ belongs_to :star
3
+
4
+ validates :name, :star, presence: true
5
+ end
@@ -0,0 +1,3 @@
1
+ class Plant < ActiveRecord::Base
2
+ validates :name, :scientific_name, presence: true
3
+ end
@@ -0,0 +1,3 @@
1
+ class Star < ActiveRecord::Base
2
+ validates :name, presence: true
3
+ end
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Dummy</title>
5
+ <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
6
+ <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
7
+ <%= csrf_meta_tags %>
8
+ </head>
9
+ <body>
10
+
11
+ <%= yield %>
12
+
13
+ </body>
14
+ </html>
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3
+ load Gem.bin_path('bundler', 'bundle')
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
3
+ require_relative '../config/boot'
4
+ require 'rails/commands'
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require_relative '../config/boot'
3
+ require 'rake'
4
+ Rake.application.run
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+ require 'pathname'
3
+
4
+ # path to your application root.
5
+ APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
6
+
7
+ Dir.chdir APP_ROOT do
8
+ # This script is a starting point to setup your application.
9
+ # Add necessary setup steps to this file:
10
+
11
+ puts "== Installing dependencies =="
12
+ system "gem install bundler --conservative"
13
+ system "bundle check || bundle install"
14
+
15
+ # puts "\n== Copying sample files =="
16
+ # unless File.exist?("config/database.yml")
17
+ # system "cp config/database.yml.sample config/database.yml"
18
+ # end
19
+
20
+ puts "\n== Preparing database =="
21
+ system "bin/rake db:setup"
22
+
23
+ puts "\n== Removing old logs and tempfiles =="
24
+ system "rm -f log/*"
25
+ system "rm -rf tmp/cache"
26
+
27
+ puts "\n== Restarting application server =="
28
+ system "touch tmp/restart.txt"
29
+ end