repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/extentions/paper_trail/auditing_adapter_spec.rb
spec/rails_admin/extentions/paper_trail/auditing_adapter_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Extensions::PaperTrail::AuditingAdapter, active_record: true do let(:controller) { double(set_paper_trail_whodunnit: nil) } describe '#initialize' do it 'accepts the user and version classes as arguments' do adapter = described_class.new(controller, User::Confirmed, Trail) expect(adapter.user_class).to eq User::Confirmed expect(adapter.version_class).to eq Trail end it 'supports block DSL' do adapter = described_class.new(controller) do user_class User::Confirmed version_class Trail sort_by(created_at: :asc) end expect(adapter.user_class).to eq User::Confirmed expect(adapter.version_class).to eq Trail expect(adapter.sort_by).to eq({created_at: :asc}) end end describe '#listing_for_model' do subject { RailsAdmin::Extensions::PaperTrail::AuditingAdapter.new(nil) } let(:model) { RailsAdmin::AbstractModel.new(PaperTrailTest) } it 'uses the given sort order' do expect_any_instance_of(ActiveRecord::Relation).to receive(:order).with(whodunnit: :asc).and_call_original subject.listing_for_model model, nil, :username, false, true, nil, 20 end it 'uses the default order when sort is not given' do expect_any_instance_of(ActiveRecord::Relation).to receive(:order).with(id: :desc).and_call_original subject.listing_for_model model, nil, false, false, true, nil, 20 end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/extentions/paper_trail/version_proxy_spec.rb
spec/rails_admin/extentions/paper_trail/version_proxy_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Extensions::PaperTrail::VersionProxy, active_record: true do describe '#username' do subject { described_class.new(version, user_class).username } let(:version) { double(whodunnit: :the_user) } let(:user_class) { double(find: user) } context 'when found user has email' do let(:user) { double(email: :mail) } it { is_expected.to eq(:mail) } end context 'when found user does not have email' do let(:user) { double } # no email method it { is_expected.to eq(:the_user) } end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/extentions/cancancan/authorization_adapter_spec.rb
spec/rails_admin/extentions/cancancan/authorization_adapter_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Extensions::CanCanCan::AuthorizationAdapter do let(:user) { double } let(:controller) { double(_current_user: user, current_ability: MyAbility.new(user)) } class MyAbility include CanCan::Ability def initialize(_user) can :access, :rails_admin can :manage, :all end end describe '#initialize' do it 'accepts the ability class as an argument' do expect(described_class.new(controller, MyAbility).ability_class).to eq MyAbility end it 'supports block DSL' do adapter = described_class.new(controller) do ability_class MyAbility end expect(adapter.ability_class).to eq MyAbility end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/const_load_suppressor_spec.rb
spec/rails_admin/config/const_load_suppressor_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::ConstLoadSuppressor do describe '.suppressing' do it 'suppresses constant loading' do expect do subject.suppressing { UnknownConstant } end.not_to raise_error end it 'raises the error on recursion' do expect do subject.suppressing do subject.suppressing {} end end.to raise_error(/already suppressed/) end end describe '.allowing' do it 'suspends constant loading suppression' do expect do subject.suppressing do subject.allowing { UnknownConstant } end end.to raise_error NameError end it 'does not break when suppression is disabled' do expect do subject.allowing {} end.not_to raise_error end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/has_description_spec.rb
spec/rails_admin/config/has_description_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::HasDescription do it 'shows description message when added through the DSL' do RailsAdmin.config do |config| config.model Team do desc 'Description of Team model' end end expect(RailsAdmin.config(Team).description).to eq('Description of Team model') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields_spec.rb
spec/rails_admin/config/fields_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields, mongoid: true do describe '.factory for self.referentials belongs_to' do it 'associates belongs_to _id foreign_key to a belongs_to association' do class MongoTree include Mongoid::Document has_many :children, class_name: name, foreign_key: :parent_id belongs_to :parent, class_name: name end expect(RailsAdmin.config(MongoTree).fields.detect { |f| f.name == :parent }.type).to eq :belongs_to_association end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/proxyable_spec.rb
spec/rails_admin/config/proxyable_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Proxyable do class ProxyableTest include RailsAdmin::Config::Proxyable def boo sleep 0.15 bindings[:foo] end def qux 'foobar' end end let!(:proxyable_test) { ProxyableTest.new } subject do proxyable_test.bindings = {foo: 'bar'} proxyable_test end it 'proxies method calls to @object' do expect(subject.bindings).to eq foo: 'bar' end it 'preserves initially set @bindings' do expect(subject.with(foo: 'baz').tap(&:qux).bindings).to eq foo: 'bar' end context 'when a method is defined in Kernel' do before do Kernel.module_eval do def qux 'quux' end end end after do Kernel.module_eval do undef qux end end it 'proxies calls for the method to @object' do expect(subject.qux).to eq 'foobar' end end describe 'with parallel execution' do it 'ensures thread-safety' do threads = Array.new(2) do |i| Thread.new do value = %w[a b][i] proxy = proxyable_test.with foo: value sleep i * 0.1 expect(proxy.boo).to eq value end end threads.each(&:join) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/actions_spec.rb
spec/rails_admin/config/actions_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Actions do describe 'default' do it 'is as before' do expect(RailsAdmin::Config::Actions.all.collect(&:key)).to eq(%i[dashboard index show new edit export delete bulk_delete history_show history_index show_in_app]) end end describe 'find' do it 'finds by custom key' do RailsAdmin.config do |config| config.actions do dashboard do custom_key :custom_dashboard end collection :custom_collection, :index show end end expect(RailsAdmin::Config::Actions.find(:custom_dashboard)).to be_a(RailsAdmin::Config::Actions::Dashboard) expect(RailsAdmin::Config::Actions.find(:custom_collection)).to be_a(RailsAdmin::Config::Actions::Index) expect(RailsAdmin::Config::Actions.find(:show)).to be_a(RailsAdmin::Config::Actions::Show) end it 'returns nil when no action is found by the custom key' do expect(RailsAdmin::Config::Actions.find(:non_existent_action_key)).to be_nil end it 'returns visible action passing binding if controller binding is given, and pass action visible or not if no' do RailsAdmin.config do |config| config.actions do root :custom_root do visible do bindings[:controller] == 'controller' end end end end expect(RailsAdmin::Config::Actions.find(:custom_root)).to be_a(RailsAdmin::Config::Actions::Base) expect(RailsAdmin::Config::Actions.find(:custom_root, controller: 'not_controller')).to be_nil expect(RailsAdmin::Config::Actions.find(:custom_root, controller: 'controller')).to be_a(RailsAdmin::Config::Actions::Base) end it "ignores bindings[:abstract_model] visibility while checking action\'s visibility" do RailsAdmin.config Team do hide end expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Comment))).to be_a(RailsAdmin::Config::Actions::Index) # decoy expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Team))).to be_a(RailsAdmin::Config::Actions::Index) end it "checks bindings[:abstract_model] presence while checking action\'s visibility" do RailsAdmin.config do |config| config.excluded_models << Team end expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Comment))).to be_a(RailsAdmin::Config::Actions::Index) # decoy expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Team))).to be_nil end end describe 'all' do it 'returns all defined actions' do RailsAdmin.config do |config| config.actions do dashboard index end end expect(RailsAdmin::Config::Actions.all.collect(&:key)).to eq(%i[dashboard index]) end it 'restricts by scope' do RailsAdmin.config do |config| config.actions do root :custom_root collection :custom_collection member :custom_member end end expect(RailsAdmin::Config::Actions.all(:root).collect(&:key)).to eq([:custom_root]) expect(RailsAdmin::Config::Actions.all(:collection).collect(&:key)).to eq([:custom_collection]) expect(RailsAdmin::Config::Actions.all(:member).collect(&:key)).to eq([:custom_member]) end it 'returns all visible actions passing binding if controller binding is given, and pass all actions if no' do RailsAdmin.config do |config| config.actions do root :custom_root do visible do bindings[:controller] == 'controller' end end end end expect(RailsAdmin::Config::Actions.all(:root).collect(&:custom_key)).to eq([:custom_root]) expect(RailsAdmin::Config::Actions.all(:root, controller: 'not_controller').collect(&:custom_key)).to eq([]) expect(RailsAdmin::Config::Actions.all(:root, controller: 'controller').collect(&:custom_key)).to eq([:custom_root]) end end describe 'customized through DSL' do it 'adds the one asked' do RailsAdmin.config do |config| config.actions do dashboard index show end end expect(RailsAdmin::Config::Actions.all.collect(&:key)).to eq(%i[dashboard index show]) end it 'allows to customize the custom_key when customizing an existing action' do RailsAdmin.config do |config| config.actions do dashboard do custom_key :my_dashboard end end end expect(RailsAdmin::Config::Actions.all.collect(&:custom_key)).to eq([:my_dashboard]) expect(RailsAdmin::Config::Actions.all.collect(&:key)).to eq([:dashboard]) end it 'allows to change the key and the custom_key when subclassing an existing action' do RailsAdmin.config do |config| config.actions do root :my_dashboard_key, :dashboard do custom_key :my_dashboard_custom_key end end end expect(RailsAdmin::Config::Actions.all.collect(&:custom_key)).to eq([:my_dashboard_custom_key]) expect(RailsAdmin::Config::Actions.all.collect(&:key)).to eq([:my_dashboard_key]) expect(RailsAdmin::Config::Actions.all.collect(&:class)).to eq([RailsAdmin::Config::Actions::Dashboard]) end it 'does not add the same custom_key twice' do expect do RailsAdmin.config do |config| config.actions do dashboard dashboard end end end.to raise_error('Action dashboard already exists. Please change its custom key.') expect do RailsAdmin.config do |config| config.actions do index collection :index end end end.to raise_error('Action index already exists. Please change its custom key.') end it 'adds the same key with different custom key' do RailsAdmin.config do |config| config.actions do dashboard dashboard do custom_key :my_dashboard end end end expect(RailsAdmin::Config::Actions.all.collect(&:custom_key)).to eq(%i[dashboard my_dashboard]) expect(RailsAdmin::Config::Actions.all.collect(&:key)).to eq(%i[dashboard dashboard]) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/model_spec.rb
spec/rails_admin/config/model_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Model do describe '#excluded?' do before do RailsAdmin.config do |config| config.included_models = [Comment] end end it 'returns false when included, true otherwise' do allow(RailsAdmin::AbstractModel).to receive(:all).and_call_original player_config = RailsAdmin.config(Player) expect(player_config.excluded?).to be_truthy expect(RailsAdmin::AbstractModel).to have_received(:all).once # Calling a second time uses the cached value. expect(player_config.excluded?).to be_truthy expect(RailsAdmin::AbstractModel).to have_received(:all).once comment_config = RailsAdmin.config(Comment) expect(comment_config.excluded?).to be_falsey expect(RailsAdmin::AbstractModel).to have_received(:all).twice # Calling a second time uses the cached value. expect(comment_config.excluded?).to be_falsey expect(RailsAdmin::AbstractModel).to have_received(:all).twice end end describe '#object_label' do before do RailsAdmin.config(Comment) do object_label_method :content end end it 'sends object_label_method to binding[:object]' do c = Comment.new(content: 'test') expect(RailsAdmin.config(Comment).with(object: c).object_label).to eq('test') end context 'when the object_label_method is blank' do it 'uses the rails admin default' do c = Comment.create(content: '', id: '1') expect(RailsAdmin.config(Comment).with(object: c).object_label).to eq('Comment #1') end end end describe '#object_label_method' do it 'is first of Config.label_methods if found as a column on model, or :rails_admin_default_object_label_method' do expect(RailsAdmin.config(Comment).object_label_method).to eq(:rails_admin_default_object_label_method) expect(RailsAdmin.config(Division).object_label_method).to eq(:name) end end describe '#label' do it 'is pretty' do expect(RailsAdmin.config(Comment).label).to eq('Comment') end end describe '#label_plural' do it 'is pretty' do expect(RailsAdmin.config(Comment).label_plural).to eq('Comments') end context 'when using i18n as label source', skip_mongoid: true do around do |example| I18n.config.available_locales = I18n.config.available_locales + [:xx] I18n.backend.class.send(:include, I18n::Backend::Pluralization) I18n.backend.store_translations :xx, activerecord: { models: { comment: { one: 'one', two: 'two', other: 'other' }, }, } I18n.locale = :xx example.run I18n.locale = :en I18n.config.available_locales = I18n.config.available_locales - [:xx] end context 'and the locale uses a specific pluralization rule' do before do I18n.backend.store_translations :xx, i18n: { plural: { rule: ->(count) do case count when 0 :zero when 1 :one when 2 :two else :other end end, }, } end it 'always uses :other as pluralization key' do expect(RailsAdmin.config(Comment).label_plural).to eq('other') end end end end describe '#weight' do it 'is 0' do expect(RailsAdmin.config(Comment).weight).to eq(0) end end describe '#parent' do it 'is nil for ActiveRecord::Base inherited models' do expect(RailsAdmin.config(Comment).parent).to be_nil end it 'is parent model otherwise' do expect(RailsAdmin.config(Hardball).parent).to eq(Ball) end end describe '#navigation_label' do it 'is nil if parent module is Object' do expect(RailsAdmin.config(Comment).navigation_label).to be_nil end it 'is parent module otherwise' do expect(RailsAdmin.config(Cms::BasicPage).navigation_label).to eq('Cms') end end describe '#last_created_at', active_record: true do let!(:teams) do [FactoryBot.create(:team, created_at: 1.day.ago), FactoryBot.create(:team, created_at: 2.days.ago)] end before do RailsAdmin.config(Team) do last_created_at { abstract_model.model.maximum(:created_at) } end end it 'allow customization' do expect(RailsAdmin.config(Team).last_created_at.to_date).to eq 1.day.ago.to_date end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/sections_spec.rb
spec/rails_admin/config/sections_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Sections do describe 'configure' do it 'configures without changing the section default list' do RailsAdmin.config Team do edit do configure :name do label 'Renamed' end end end fields = RailsAdmin.config(Team).edit.fields expect(fields.detect { |f| f.name == :name }.label).to eq('Renamed') expect(fields.count).to be >= 19 # not 1 end it 'does not change the section list if set' do RailsAdmin.config Team do edit do field :manager configure :name do label 'Renamed' end end end fields = RailsAdmin.config(Team).edit.fields expect(fields.first.name).to eq(:manager) expect(fields.count).to eq(1) # not 19 end end describe 'DSL field inheritance' do it 'is tested' do RailsAdmin.config do |config| config.model Fan do field :name do label do @label ||= "modified base #{label}" end end list do field :name do label do @label ||= "modified list #{label}" end end end edit do field :name do label do @label ||= "modified edit #{label}" end end end create do field :name do label do @label ||= "modified create #{label}" end end end end end expect(RailsAdmin.config(Fan).visible_fields.count).to eq(1) expect(RailsAdmin.config(Fan).visible_fields.first.label).to eq('modified base Their Name') expect(RailsAdmin.config(Fan).list.visible_fields.first.label).to eq('modified list Their Name') expect(RailsAdmin.config(Fan).export.visible_fields.first.label).to eq('modified base Their Name') expect(RailsAdmin.config(Fan).edit.visible_fields.first.label).to eq('modified edit Their Name') expect(RailsAdmin.config(Fan).create.visible_fields.first.label).to eq('modified create Their Name') expect(RailsAdmin.config(Fan).update.visible_fields.first.label).to eq('modified edit Their Name') end end describe 'DSL group inheritance' do it 'is tested' do RailsAdmin.config do |config| config.model Team do list do group 'a' do field :founded end group 'b' do field :name field :wins end end edit do group 'a' do field :name end group 'c' do field :founded field :wins end end update do group 'd' do field :wins end group 'e' do field :losses end end end end expect(RailsAdmin.config(Team).list.visible_groups.collect { |g| g.visible_fields.collect(&:name) }).to eq([[:founded], %i[name wins]]) expect(RailsAdmin.config(Team).edit.visible_groups.collect { |g| g.visible_fields.collect(&:name) }).to eq([[:name], %i[founded wins]]) expect(RailsAdmin.config(Team).create.visible_groups.collect { |g| g.visible_fields.collect(&:name) }).to eq([[:name], %i[founded wins]]) expect(RailsAdmin.config(Team).update.visible_groups.collect { |g| g.visible_fields.collect(&:name) }).to eq([[:name], [:founded], [:wins], [:losses]]) expect(RailsAdmin.config(Team).visible_groups.collect { |g| g.visible_fields.collect(&:name) }.flatten.count).to eq(20) expect(RailsAdmin.config(Team).export.visible_groups.collect { |g| g.visible_fields.collect(&:name) }.flatten.count).to eq(20) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/lazy_model_spec.rb
spec/rails_admin/config/lazy_model_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::LazyModel do subject { RailsAdmin::Config::LazyModel.new(:Team, &block) } let(:block) { proc { register_instance_option('parameter') } } # an arbitrary instance method we can spy on describe '#initialize' do it "doesn't evaluate the block immediately" do expect_any_instance_of(RailsAdmin::Config::Model).not_to receive(:register_instance_option) subject end it 'evaluates block when reading' do expect_any_instance_of(RailsAdmin::Config::Model).to receive(:register_instance_option).with('parameter') subject.groups # an arbitrary instance method on RailsAdmin::Config::Model to wake up lazy_model end it 'evaluates config block only once' do expect_any_instance_of(RailsAdmin::Config::Model).to receive(:register_instance_option).once.with('parameter') subject.groups subject.groups end end describe '#add_deferred_block' do let(:another_block) { proc { register_instance_option('parameter2') } } it "doesn't evaluate the block immediately" do expect_any_instance_of(RailsAdmin::Config::Model).not_to receive(:register_instance_option).with('parameter2') subject.add_deferred_block(&another_block) end it 'evaluates the block immediately after initialization' do subject.target expect_any_instance_of(RailsAdmin::Config::Model).to receive(:register_instance_option).with('parameter2') subject.add_deferred_block(&another_block) end end context 'when a method is defined in Kernel' do before do Kernel.module_eval do def weight 42 end end end after do Kernel.module_eval do undef weight end end it 'proxies calls for the method to @object' do expect(subject.weight).to eq 0 end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/has_fields_spec.rb
spec/rails_admin/config/has_fields_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::HasFields do it 'shows hidden fields when added through the DSL' do expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :division_id }).not_to be_visible RailsAdmin.config do |config| config.model Team do field :division_id end end expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :division_id }).to be_visible end it 'does not set visibility for fields with bindings' do RailsAdmin.config do |config| config.model Team do field :division do visible do bindings[:controller].current_user.email == 'test@email.com' end end end end expect { RailsAdmin.config(Team).fields.detect { |f| f.name == :division } }.not_to raise_error expect { RailsAdmin.config(Team).fields.detect { |f| f.name == :division }.visible? }.to raise_error(/undefined method [`']\[\]' for nil/) end it 'assigns properties to new one on overriding existing field' do RailsAdmin.config do |config| config.model Team do field :players, :has_and_belongs_to_many_association end end expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :players }.properties).not_to be_nil end describe '#configure' do it 'does not change the order of existing fields, if some field types of them are changed' do original_fields_order = RailsAdmin.config(Team).fields.map(&:name) RailsAdmin.config do |config| config.model Team do configure :players, :enum do enum { [] } end configure :revenue, :integer end end expect(RailsAdmin.config(Team).fields.map(&:name)).to eql(original_fields_order) end it 'allows passing multiple fields to share the same configuration' do target_field_names = %i[players revenue] original_config = RailsAdmin.config(Team).fields.select { |field| target_field_names.include?(field.name) } original_config.each { |field| expect(field).to be_visible } RailsAdmin.config do |config| config.model Team do configure target_field_names do visible false end end end updated_config = RailsAdmin.config(Team).fields.select { |field| target_field_names.include?(field.name) } updated_config.each { |field| expect(field).to_not be_visible } end end describe '#_fields' do let(:config) { RailsAdmin.config(Team) } before do RailsAdmin.config(Team) do field :id field :wins, :boolean end end it "does not cause FrozenError by changing exiting field's type" do # Reference the fields for readonly config.edit.send(:_fields, true) RailsAdmin.config(Team) do field :wins, :integer end expect(config.fields.map(&:name)).to match_array %i[id wins] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/configurable_spec.rb
spec/rails_admin/config/configurable_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Configurable do class ConfigurableTest include RailsAdmin::Config::Configurable register_instance_option :foo do 'default' end end subject { ConfigurableTest.new } describe 'recursion tracking' do it 'works and use default value' do subject.instance_eval do foo { foo } end expect(subject.foo).to eq 'default' end describe 'with parallel execution' do before do subject.instance_eval do foo do sleep 0.15 'value' end end end it 'ensures thread-safety' do threads = Array.new(2) do |i| Thread.new do sleep i * 0.1 expect(subject.foo).to eq 'value' end end threads.each(&:join) end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/sections/list_spec.rb
spec/rails_admin/config/sections/list_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Sections::List do describe '#fields_for_table' do subject { RailsAdmin.config(Player).list } it 'brings sticky fields first' do RailsAdmin.config Player do list do field(:number) field(:id) field(:name) { sticky true } end end expect(subject.fields_for_table.map(&:name)).to eq %i[name number id] end it 'keep the original order except for stickey ones' do RailsAdmin.config Player do list do configure(:number) { sticky true } end end expect(subject.fields_for_table.map(&:name)).to eq %i[number] + (subject.visible_fields.map(&:name) - %i[number]) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/actions/base_spec.rb
spec/rails_admin/config/actions/base_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Actions::Base do describe '#enabled?' do it 'excludes models not referenced in the only array' do RailsAdmin.config do |config| config.actions do index do only [Player, Cms::BasicPage] end end end expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Player))).to be_enabled expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Team))).to be_nil expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Cms::BasicPage))).to be_enabled end it 'excludes models referenced in the except array' do RailsAdmin.config do |config| config.actions do index do except [Player, Cms::BasicPage] end end end expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Player))).to be_nil expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Team))).to be_enabled expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Cms::BasicPage))).to be_nil end it 'is always true for a writable model' do RailsAdmin.config do |config| config.actions do index show new edit delete end end %i[index show new edit delete].each do |action| expect(RailsAdmin::Config::Actions.find(action, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(Player), object: Player.new)).to be_enabled end end it 'is false for write operations of a read-only model' do RailsAdmin.config do |config| config.actions do index show new edit delete end end expect(RailsAdmin::Config::Actions.find(:index, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(ReadOnlyComment))).to be_enabled expect(RailsAdmin::Config::Actions.find(:show, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(ReadOnlyComment), object: ReadOnlyComment.new)).to be_enabled expect(RailsAdmin::Config::Actions.find(:new, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(ReadOnlyComment))).to be_enabled expect(RailsAdmin::Config::Actions.find(:edit, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(ReadOnlyComment), object: ReadOnlyComment.new)).to be_nil expect(RailsAdmin::Config::Actions.find(:delete, controller: double(authorized?: true), abstract_model: RailsAdmin::AbstractModel.new(ReadOnlyComment), object: ReadOnlyComment.new)).to be_nil end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/association_spec.rb
spec/rails_admin/config/fields/association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Association do describe '#pretty_value' do let(:player) { FactoryBot.create(:player, name: '<br />', team: FactoryBot.create(:team)) } let(:field) { RailsAdmin.config('Team').fields.detect { |f| f.name == :players } } let(:view) { ActionView::Base.empty } subject { field.with(object: player.team, view: view).pretty_value } context 'when the link is disabled' do let(:view) { ActionView::Base.empty.tap { |d| allow(d).to receive(:action).and_return(nil) } } it 'does not expose non-HTML-escaped string' do is_expected.to be_html_safe is_expected.to eq '&lt;br /&gt;' end end context 'when the value is empty' do let(:team) { FactoryBot.build :team } subject { field.with(object: team, view: view).pretty_value } it "returns '-' to show emptiness" do is_expected.to eq '-' end end end describe '#dynamic_scope_relationships' do let(:player) { FactoryBot.create(:player, team: FactoryBot.create(:team)) } let(:field) { RailsAdmin.config('Draft').fields.detect { |f| f.name == :player } } it 'returns the relationship of fields in this model and in the associated model' do RailsAdmin.config Draft do field :team field :player do dynamically_scope_by :team end end expect(field.dynamic_scope_relationships).to eq({team_id: :team}) end it 'accepts Array' do RailsAdmin.config Draft do field :team field :notes field :player do dynamically_scope_by %i[team notes] end end expect(field.dynamic_scope_relationships).to eq({team_id: :team, notes: :notes}) end it 'accepts Hash' do RailsAdmin.config Draft do field :round field :player do dynamically_scope_by({round: :number}) end end expect(field.dynamic_scope_relationships).to eq({round: :number}) end it 'accepts mixture of Array and Hash' do RailsAdmin.config Draft do field :team field :round field :player do dynamically_scope_by [:team, {round: :number}] end end expect(field.dynamic_scope_relationships).to eq({team_id: :team, round: :number}) end it 'raises error if the field does not exist in this model' do RailsAdmin.config Draft do field :player do dynamically_scope_by :team end end expect { field.dynamic_scope_relationships }.to raise_error "Field 'team' was given for #dynamically_scope_by but not found in 'Draft'" end it 'raises error if the field does not exist in the associated model' do RailsAdmin.config Player do field :name end RailsAdmin.config Draft do field :team field :player do dynamically_scope_by :team end end expect { field.dynamic_scope_relationships }.to raise_error "Field 'team' was given for #dynamically_scope_by but not found in 'Player'" end it 'raises error if the target field is not filterable' do RailsAdmin.config Player do field :name field :team do filterable false end end RailsAdmin.config Draft do field :team field :player do dynamically_scope_by :team end end expect { field.dynamic_scope_relationships }.to raise_error "Field 'team' in 'Player' can't be used for dynamic scoping because it's not filterable" end end describe '#removable?', active_record: true do context 'with non-nullable foreign key' do let(:field) { RailsAdmin.config('FieldTest').fields.detect { |f| f.name == :nested_field_tests } } it 'is false' do expect(field.removable?).to be false end end context 'with nullable foreign key' do let(:field) { RailsAdmin.config('Team').fields.detect { |f| f.name == :players } } it 'is true' do expect(field.removable?).to be true end end context 'with polymorphic has_many' do let(:field) { RailsAdmin.config('Player').fields.detect { |f| f.name == :comments } } it 'does not break' do expect(field.removable?).to be true end end context 'with has_many through' do before do class TeamWithHasManyThrough < Team has_many :drafts has_many :draft_players, through: :drafts, source: :player end end let(:field) { RailsAdmin.config('TeamWithHasManyThrough').fields.detect { |f| f.name == :draft_players } } it 'does not break' do expect(field.removable?).to be true end end end describe '#value' do context 'when using `system` as the association name' do before do class System < Tableless; end class BelongsToSystem < Tableless column :system_id, :integer belongs_to :system end end let(:record) { BelongsToSystem.new(system: System.new) } let(:field) { RailsAdmin.config(BelongsToSystem).fields.detect { |f| f.name == :system } } subject { field.with(object: record).value } it 'does not break' do expect(subject).to be_a_kind_of System end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/base_spec.rb
spec/rails_admin/config/fields/base_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Base do describe '#required' do it 'reads the on: :create/:update validate option' do RailsAdmin.config Ball do field 'color' end expect(RailsAdmin.config('Ball').fields.first.with(object: Ball.new)).to be_required expect(RailsAdmin.config('Ball').fields.first.with(object: FactoryBot.create(:ball))).not_to be_required end context 'without validation' do it 'is optional' do # draft.notes is nullable and has no validation field = RailsAdmin.config('Draft').edit.fields.detect { |f| f.name == :notes } expect(field.properties.nullable?).to be_truthy expect(field.required?).to be_falsey end end context 'with presence validation' do it 'is required' do # draft.date is nullable in the schema but has an AR # validates_presence_of validation that makes it required field = RailsAdmin.config('Draft').edit.fields.detect { |f| f.name == :date } expect(field.properties.nullable?).to be_truthy expect(field.required?).to be_truthy end end context 'with numericality validation' do it 'is required' do # draft.round is nullable in the schema but has an AR # validates_numericality_of validation that makes it required field = RailsAdmin.config('Draft').edit.fields.detect { |f| f.name == :round } expect(field.properties.nullable?).to be_truthy expect(field.required?).to be_truthy end end context 'with validation marked as allow_nil or allow_blank' do it 'is optional' do # team.revenue is nullable in the schema but has an AR # validates_numericality_of validation that allows nil field = RailsAdmin.config('Team').edit.fields.detect { |f| f.name == :revenue } expect(field.properties.nullable?).to be_truthy expect(field.required?).to be_falsey # team.founded is nullable in the schema but has an AR # validates_numericality_of validation that allows blank field = RailsAdmin.config('Team').edit.fields.detect { |f| f.name == :founded } expect(field.properties.nullable?).to be_truthy expect(field.required?).to be_falsey end end context 'with conditional validation' do before do class ConditionalValidationTest < Tableless column :foo, :varchar column :bar, :varchar validates :foo, presence: true, if: :persisted? validates :bar, presence: true, unless: :persisted? end end it 'is optional' do expect(RailsAdmin.config('ConditionalValidationTest').fields.detect { |f| f.name == :foo }).not_to be_required expect(RailsAdmin.config('ConditionalValidationTest').fields.detect { |f| f.name == :bar }).not_to be_required end end context 'on a Paperclip installation' do it 'should detect required fields' do expect(RailsAdmin.config('Image').fields.detect { |f| f.name == :file }.with(object: Image.new)).to be_required end end describe 'associations' do before do class RelTest < Tableless column :league_id, :integer column :division_id, :integer, nil, false column :player_id, :integer belongs_to :league, optional: true belongs_to :division, optional: true belongs_to :player, optional: true validates_numericality_of(:player_id, only_integer: true) end @fields = RailsAdmin.config(RelTest).create.fields end describe 'for column with nullable foreign key and no model validations' do it 'is optional' do expect(@fields.detect { |f| f.name == :league }.required?).to be_falsey end end describe 'for column with non-nullable foreign key and no model validations' do it 'is optional' do expect(@fields.detect { |f| f.name == :division }.required?).to be_falsey end end describe 'for column with nullable foreign key and a numericality model validation' do it 'is required' do expect(@fields.detect { |f| f.name == :player }.required?).to be_truthy end end end end describe '#name' do it 'is normalized to Symbol' do RailsAdmin.config Team do field 'name' end expect(RailsAdmin.config('Team').fields.first.name).to eq(:name) end end describe '#children_fields' do POLYMORPHIC_CHILDREN = %i[commentable_id commentable_type].freeze it 'is empty by default' do expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :name }.children_fields).to eq([]) end it 'contains child key for belongs to associations' do expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :division }.children_fields).to eq([:division_id]) end it 'contains child keys for polymorphic belongs to associations' do expect(RailsAdmin.config(Comment).fields.detect { |f| f.name == :commentable }.children_fields).to match_array POLYMORPHIC_CHILDREN end it 'has correct fields when polymorphic_type column comes ahead of polymorphic foreign_key column' do class CommentReversed < Tableless column :commentable_type, :varchar column :commentable_id, :integer belongs_to :commentable, polymorphic: true end expect(RailsAdmin.config(CommentReversed).fields.collect { |f| f.name.to_s }.select { |f| /^comment/ =~ f }).to match_array ['commentable'].concat(POLYMORPHIC_CHILDREN.collect(&:to_s)) end context 'of a Paperclip installation' do it 'is a _file_name field' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :paperclip_asset }.children_fields.include?(:paperclip_asset_file_name)).to be_truthy end it 'is hidden, not filterable' do field = RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :paperclip_asset_file_name } expect(field.hidden?).to be_truthy expect(field.filterable?).to be_falsey end end context 'of a Dragonfly installation' do it 'is a _name field and _uid field' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :dragonfly_asset }.children_fields).to eq(%i[dragonfly_asset_name dragonfly_asset_uid]) end end context 'of a Carrierwave installation' do it 'is the parent field itself' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :carrierwave_asset }.children_fields).to eq([:carrierwave_asset]) expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :carrierwave_asset }.hidden?).to be_falsey end end context 'of a Carrierwave installation with multiple file support' do it 'is the parent field itself' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :carrierwave_assets }.children_fields).to eq([:carrierwave_assets]) expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :carrierwave_assets }.hidden?).to be_falsey end end if defined?(ActiveStorage) context 'of a ActiveStorage installation' do it 'is _attachment and _blob fields' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :active_storage_asset }.children_fields).to match_array %i[active_storage_asset_attachment active_storage_asset_blob] end it 'is hidden, not filterable' do fields = RailsAdmin.config(FieldTest).fields.select { |f| %i[active_storage_asset_attachment active_storage_asset_blob].include?(f.name) } expect(fields).to all(be_hidden) expect(fields).not_to include(be_filterable) end end context 'of a ActiveStorage installation with multiple file support' do it 'is _attachment and _blob fields' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :active_storage_assets }.children_fields).to match_array %i[active_storage_assets_attachments active_storage_assets_blobs] end it 'is hidden, not filterable' do fields = RailsAdmin.config(FieldTest).fields.select { |f| %i[active_storage_assets_attachments active_storage_assets_blobs].include?(f.name) } expect(fields).to all(be_hidden) expect(fields).not_to include(be_filterable) end end end if defined?(Shrine) context 'of a Shrine installation' do it 'is the parent field itself' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :shrine_asset }.children_fields).to eq([:shrine_asset_data]) expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :shrine_asset }.hidden?).to be_falsey end it 'is not filterable' do fields = RailsAdmin.config(FieldTest).fields.select { |f| [:shrine_asset_data].include?(f.name) } expect(fields).to all(be_hidden) expect(fields).not_to include(be_filterable) end end end end describe '#form_default_value' do it 'is default_value for new records when value is nil' do RailsAdmin.config Team do list do field :name do default_value 'default value' end end end @team = Team.new expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :name }.with(object: @team).form_default_value).to eq('default value') @team.name = 'set value' expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :name }.with(object: @team).form_default_value).to be_nil @team = FactoryBot.create :team @team.name = nil expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :name }.with(object: @team).form_default_value).to be_nil end end describe '#default_value' do it 'is nil by default' do expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :name }.default_value).to be_nil end end describe '#hint' do it 'is user customizable' do RailsAdmin.config Team do list do field :division do hint 'Great Division' end field :name end end expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :division }.hint).to eq('Great Division') # custom expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :name }.hint).to eq('') # default end end describe '#help' do it 'has a default and be user customizable via i18n' do RailsAdmin.config Team do list do field :division field :name end end field_specific_i18n = RailsAdmin.config('Team').list.fields.detect { |f| f.name == :name } expect(field_specific_i18n.help).to eq(I18n.translate('admin.help.team.name')) # custom via locales yml field_no_specific_i18n = RailsAdmin.config('Team').list.fields.detect { |f| f.name == :division } expect(field_no_specific_i18n.help).to eq(field_no_specific_i18n.generic_help) # rails_admin generic fallback end end describe '#css_class' do it 'has a default and be user customizable' do RailsAdmin.config Team do list do field :division do css_class 'custom' end field :name end end expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :division }.css_class).to eq('custom') # custom expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :division }.type_css_class).to eq('belongs_to_association_type') # type css class, non-customizable expect(RailsAdmin.config('Team').list.fields.detect { |f| f.name == :name }.css_class).to eq('name_field') # default end end describe '#associated_collection_cache_all' do it 'defaults to true if associated collection count < 100' do expect(RailsAdmin.config(Team).edit.fields.detect { |f| f.name == :players }.associated_collection_cache_all).to be_truthy end it 'defaults to false if associated collection count >= 100' do @players = Array.new(100) do FactoryBot.create :player end expect(RailsAdmin.config(Team).edit.fields.detect { |f| f.name == :players }.associated_collection_cache_all).to be_falsey end context 'with custom configuration' do before do RailsAdmin.config.default_associated_collection_limit = 5 end it 'defaults to true if associated collection count less than than limit' do @players = Array.new(4) do FactoryBot.create :player end expect(RailsAdmin.config(Team).edit.fields.detect { |f| f.name == :players }.associated_collection_cache_all).to be_truthy end it 'defaults to false if associated collection count >= that limit' do @players = Array.new(5) do FactoryBot.create :player end expect(RailsAdmin.config(Team).edit.fields.detect { |f| f.name == :players }.associated_collection_cache_all).to be_falsey end end end describe '#searchable_columns' do describe 'for belongs_to fields' do it 'finds label method on the opposite side for belongs_to associations by default' do expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :division }.searchable_columns.collect { |c| c[:column] }).to eq(['divisions.name', 'teams.division_id']) end it 'searches on opposite table for belongs_to' do RailsAdmin.config(Team) do field :division do searchable :custom_id end end expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :division }.searchable_columns.collect { |c| c[:column] }).to eq(['divisions.custom_id']) end it 'searches on asked table with model name' do RailsAdmin.config(Team) do field :division do searchable League => :name end end expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :division }.searchable_columns).to eq([{column: 'leagues.name', type: :string}]) end it 'searches on asked table with table name' do RailsAdmin.config(Team) do field :division do searchable leagues: :name end end expect(RailsAdmin.config(Team).fields.detect { |f| f.name == :division }.searchable_columns).to eq([{column: 'leagues.name', type: :string}]) end end describe 'for basic type fields' do it 'uses base table and find correct column type' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :text_field }.searchable_columns).to eq([{column: 'field_tests.text_field', type: :text}]) expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :integer_field }.searchable_columns).to eq([{column: 'field_tests.integer_field', type: :integer}]) end it 'is customizable to another field on the same table' do RailsAdmin.config(FieldTest) do field :time_field do searchable :date_field end end expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :time_field }.searchable_columns).to eq([{column: 'field_tests.date_field', type: :date}]) end it 'is customizable to another field on another table with :table_name' do RailsAdmin.config(FieldTest) do field :string_field do searchable nested_field_tests: :title end end expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :string_field }.searchable_columns).to eq([{column: 'nested_field_tests.title', type: :string}]) end it 'is customizable to another field on another model with ModelClass' do RailsAdmin.config(FieldTest) do field :string_field do searchable NestedFieldTest => :title end end expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :string_field }.searchable_columns).to eq([{column: 'nested_field_tests.title', type: :string}]) end end describe 'for mapped fields' do it 'of paperclip should find the underlying column on the base table' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :paperclip_asset }.searchable_columns.collect { |c| c[:column] }).to eq(['field_tests.paperclip_asset_file_name']) end it 'of dragonfly should find the underlying column on the base table' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :dragonfly_asset }.searchable_columns.collect { |c| c[:column] }).to eq(['field_tests.dragonfly_asset_name']) end it 'of carrierwave should find the underlying column on the base table' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :carrierwave_asset }.searchable_columns.collect { |c| c[:column] }).to eq(['field_tests.carrierwave_asset']) end end end describe '#searchable and #sortable' do it 'is false if column is virtual, true otherwise' do RailsAdmin.config League do field :virtual_column field :name end @league = FactoryBot.create :league expect(RailsAdmin.config('League').export.fields.detect { |f| f.name == :virtual_column }.sortable).to be_falsey expect(RailsAdmin.config('League').export.fields.detect { |f| f.name == :virtual_column }.searchable).to be_falsey expect(RailsAdmin.config('League').export.fields.detect { |f| f.name == :name }.sortable).to be_truthy expect(RailsAdmin.config('League').export.fields.detect { |f| f.name == :name }.searchable).to be_truthy end context 'of a virtual field with children fields' do it 'of paperclip should target the first children field' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :paperclip_asset }.searchable).to eq(:paperclip_asset_file_name) expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :paperclip_asset }.sortable).to eq(:paperclip_asset_file_name) end it 'of dragonfly should target the first children field' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :dragonfly_asset }.searchable).to eq(:dragonfly_asset_name) expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :dragonfly_asset }.sortable).to eq(:dragonfly_asset_name) end it 'of carrierwave should target the first children field' do expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :carrierwave_asset }.searchable).to eq(:carrierwave_asset) expect(RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :carrierwave_asset }.sortable).to eq(:carrierwave_asset) end end end describe '#virtual?' do it 'is true if column has no properties, false otherwise' do RailsAdmin.config League do field :virtual_column field :name end @league = FactoryBot.create :league expect(RailsAdmin.config('League').export.fields.detect { |f| f.name == :virtual_column }.virtual?).to be_truthy expect(RailsAdmin.config('League').export.fields.detect { |f| f.name == :name }.virtual?).to be_falsey end end describe '#default_search_operator' do let(:abstract_model) { RailsAdmin::AbstractModel.new('Player') } let(:model_config) { RailsAdmin.config(abstract_model) } let(:queryable_fields) { model_config.list.fields.select(&:queryable?) } context 'when no search operator is specified for the field' do it "uses 'default' search operator" do expect(queryable_fields.size).to be >= 1 expect(queryable_fields.first.search_operator).to eq(RailsAdmin::Config.default_search_operator) end it 'uses config.default_search_operator if set' do RailsAdmin.config do |config| config.default_search_operator = 'starts_with' end expect(queryable_fields.size).to be >= 1 expect(queryable_fields.first.search_operator).to eq(RailsAdmin::Config.default_search_operator) end end context 'when search operator is specified for the field' do it 'uses specified search operator' do RailsAdmin.config Player do list do fields do search_operator 'starts_with' end end end expect(queryable_fields.size).to be >= 1 expect(queryable_fields.first.search_operator).to eq('starts_with') end it 'uses specified search operator even if config.default_search_operator set' do RailsAdmin.config do |config| config.default_search_operator = 'starts_with' config.model Player do list do fields do search_operator 'ends_with' end end end end expect(queryable_fields.size).to be >= 1 expect(queryable_fields.first.search_operator).to eq('ends_with') end end end describe '#render' do it 'is configurable' do RailsAdmin.config Team do field :name do render do 'rendered' end end end expect(RailsAdmin.config(Team).field(:name).render).to eq('rendered') end end describe '#active' do it 'is false by default' do expect(RailsAdmin.config(Team).field(:division).active?).to be_falsey end end describe '#visible?' do it 'is false when fields have specific name ' do class FieldVisibilityTest < Tableless column :id, :integer column :_id, :integer column :_type, :varchar column :name, :varchar column :created_at, :timestamp column :updated_at, :timestamp column :deleted_at, :timestamp column :created_on, :timestamp column :updated_on, :timestamp column :deleted_on, :timestamp end expect(RailsAdmin.config(FieldVisibilityTest).base.fields.select(&:visible?).collect(&:name)).to match_array %i[_id created_at created_on deleted_at deleted_on id name updated_at updated_on] expect(RailsAdmin.config(FieldVisibilityTest).list.fields.select(&:visible?).collect(&:name)).to match_array %i[_id created_at created_on deleted_at deleted_on id name updated_at updated_on] expect(RailsAdmin.config(FieldVisibilityTest).edit.fields.select(&:visible?).collect(&:name)).to match_array [:name] expect(RailsAdmin.config(FieldVisibilityTest).show.fields.select(&:visible?).collect(&:name)).to match_array [:name] end end describe '#allowed_methods' do it 'includes method_name' do RailsAdmin.config do |config| config.model Team do field :name end end expect(RailsAdmin.config(Team).field(:name).allowed_methods).to eq [:name] end end describe '#default_filter_operator' do it 'has a default and be user customizable' do RailsAdmin.config Team do list do field :division field :name do default_filter_operator 'is' end end end name_field = RailsAdmin.config('Team').list.fields.detect { |f| f.name == :name } expect(name_field.default_filter_operator).to eq('is') # custom via user specification division_field = RailsAdmin.config('Team').list.fields.detect { |f| f.name == :division } expect(division_field.default_filter_operator).to be nil # rails_admin generic fallback end end describe '#eager_load' do let(:field) { RailsAdmin.config('Team').fields.detect { |f| f.name == :players } } it 'can be set to true' do RailsAdmin.config Team do field :players do eager_load true end end expect(field.eager_load_values).to eq [:players] end it 'can be set to false' do RailsAdmin.config Team do field :players do eager_load false end end expect(field.eager_load_values).to eq [] end it 'can be set to a custom value' do RailsAdmin.config Team do field :players do eager_load [{players: :draft}, :fans] end end expect(field.eager_load_values).to eq [{players: :draft}, :fans] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/uuid_spec.rb
spec/rails_admin/config/fields/types/uuid_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Uuid do let(:uuid) { SecureRandom.uuid } let(:object) { FactoryBot.create(:field_test) } let(:field) { RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :uuid_field } } before do RailsAdmin.config do |config| config.model FieldTest do field :uuid_field, :uuid end end allow(object).to receive(:uuid_field).and_return uuid field.bindings = {object: object} end it 'field is a Uuid fieldtype' do expect(field.class).to eq RailsAdmin::Config::Fields::Types::Uuid end it 'handles uuid string' do expect(field.value).to eq uuid end it_behaves_like 'a generic field type', :string_field, :uuid end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/code_mirror_spec.rb
spec/rails_admin/config/fields/types/code_mirror_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::CodeMirror do it_behaves_like 'a generic field type', :text_field, :code_mirror it_behaves_like 'a string-like field type', :text_field, :code_mirror end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/multiple_file_upload_spec.rb
spec/rails_admin/config/fields/types/multiple_file_upload_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::MultipleFileUpload do it_behaves_like 'a generic field type', :string_field, :multiple_file_upload describe '#allowed_methods' do it 'includes delete_method and cache_method' do RailsAdmin.config do |config| config.model FieldTest do field :carrierwave_assets, :multiple_carrierwave if defined?(ActiveStorage) field :active_storage_assets, :multiple_active_storage do delete_method :remove_active_storage_assets end end end end expect(RailsAdmin.config(FieldTest).field(:carrierwave_assets).with(object: FieldTest.new).allowed_methods.collect(&:to_s)).to eq %w[carrierwave_assets] expect(RailsAdmin.config(FieldTest).field(:active_storage_assets).with(object: FieldTest.new).allowed_methods.collect(&:to_s)).to eq %w[active_storage_assets remove_active_storage_assets] if defined?(ActiveStorage) end end describe '#html_attributes' do context 'when the field is required and value is already set' do before do RailsAdmin.config FieldTest do field :string_field, :multiple_file_upload do required true end end end let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with(object: FieldTest.new(string_field: 'dummy.jpg')) end it 'does not have a required attribute' do expect(rails_admin_field.html_attributes[:required]).to be_falsy end end end describe '#pretty_value' do before do RailsAdmin.config FieldTest do field :string_field, :multiple_file_upload do attachment do thumb_method 'thumb' def resource_url(thumb = false) if thumb "http://example.com/#{thumb}/#{value}" else "http://example.com/#{value}" end end end end end end let(:filename) { '' } let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with( object: FieldTest.new(string_field: filename), view: ApplicationController.new.view_context, ) end context 'when the field is not an image' do let(:filename) { 'dummy.txt' } it 'uses filename as link text' do expect(Nokogiri::HTML(rails_admin_field.pretty_value).text).to eq 'dummy.txt' end end context 'when the field is an image' do let(:filename) { 'dummy.jpg' } subject { Nokogiri::HTML(rails_admin_field.pretty_value) } it 'shows thumbnail image with a link' do expect(subject.css('img').attribute('src').value).to eq 'http://example.com/thumb/dummy.jpg' expect(subject.css('a').attribute('href').value).to eq 'http://example.com/dummy.jpg' end end end describe '#attachment' do before do RailsAdmin.config FieldTest do field :string_field, :multiple_file_upload do attachment do delete_value 'something' def resource_url(_thumb = false) "http://example.com/#{value}" end end def value ['foo.jpg'] end end end end let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with( view: ApplicationController.new.view_context, ) end it 'enables configuration' do expect(rails_admin_field.attachments.map(&:delete_value)).to eq ['something'] expect(rails_admin_field.attachments.map(&:resource_url)).to eq ['http://example.com/foo.jpg'] expect(rails_admin_field.pretty_value).to match(%r{src="http://example.com/foo.jpg"}) end end describe '#attachments' do before do RailsAdmin.config FieldTest do field :string_field, :multiple_file_upload end end let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end end it 'wraps value with Array()' do expect(rails_admin_field.with(object: FieldTest.new(string_field: nil)).attachments).to eq [] expect(rails_admin_field.with(object: FieldTest.new(string_field: 'dummy.txt')).attachments.map(&:value)).to eq ['dummy.txt'] end end describe '#image?' do let(:filename) { 'dummy.txt' } let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with( object: FieldTest.new(string_field: filename), view: ApplicationController.new.view_context, ) end before do RailsAdmin.config FieldTest do field :string_field, :multiple_file_upload do attachment do def resource_url "http://example.com/#{value}" end end end end end context 'when the file is not an image' do let(:filename) { 'dummy.txt' } it 'returns false' do expect(rails_admin_field.attachments.first.image?).to be false end end context 'when the file is an image' do let(:filename) { 'dummy.jpg' } it 'returns true' do expect(rails_admin_field.attachments.first.image?).to be true end end context 'when the file is an image but suffixed with a query string' do let(:filename) { 'dummy.jpg?foo=bar' } it 'returns true' do expect(rails_admin_field.attachments.first.image?).to be true end end context "when the filename can't be represented as a valid URI" do let(:filename) { 'du mmy.jpg' } it 'returns false' do expect(rails_admin_field.attachments.first.image?).to be false end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/string_spec.rb
spec/rails_admin/config/fields/types/string_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::String do describe '#html_attributes' do before :each do RailsAdmin.config Ball do field 'color', :string end end let(:string_field) do RailsAdmin.config('Ball').fields.detect do |f| f.name == :color end.with(object: Ball.new) end it 'should contain a size attribute' do expect(string_field.html_attributes[:size]).to be_present end it 'should not contain a size attribute valorized with 0' do expect(string_field.html_attributes[:size]).to_not be_zero end end it_behaves_like 'a generic field type', :string_field it_behaves_like 'a string-like field type', :string_field end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/bson_object_id_spec.rb
spec/rails_admin/config/fields/types/bson_object_id_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::BsonObjectId do it_behaves_like 'a generic field type', :string_field, :bson_object_id describe '#parse_value' do let(:bson) { RailsAdmin::Adapters::Mongoid::Bson::OBJECT_ID.new } let(:field) do RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :bson_object_id_field end end before :each do RailsAdmin.config do |config| config.model FieldTest do field :bson_object_id_field, :bson_object_id end end end it 'parse valid bson_object_id', mongoid: true do expect(field.parse_value(bson.to_s)).to eq bson end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/text_spec.rb
spec/rails_admin/config/fields/types/text_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Text do it_behaves_like 'a generic field type', :text_field it_behaves_like 'a string-like field type', :text_field end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/string_like_spec.rb
spec/rails_admin/config/fields/types/string_like_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::StringLike do describe '#treat_empty_as_nil?', active_record: true do context 'with a nullable field' do subject do RailsAdmin.config('Team').fields.detect do |f| f.name == :name end.with(object: Team.new) end it 'is true' do expect(subject.treat_empty_as_nil?).to be true end end context 'with a non-nullable field' do subject do RailsAdmin.config('Team').fields.detect do |f| f.name == :manager end.with(object: Team.new) end it 'is false' do expect(subject.treat_empty_as_nil?).to be false end end end describe '#parse_input' do subject do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with(object: FieldTest.new) end context 'with treat_empty_as_nil being true' do before do RailsAdmin.config FieldTest do field :string_field do treat_empty_as_nil true end end end context 'when value is empty' do let(:params) { {string_field: ''} } it 'makes the value nil' do subject.parse_input(params) expect(params.key?(:string_field)).to be true expect(params[:string_field]).to be nil end end context 'when value does not exist in params' do let(:params) { {} } it 'does not touch params' do subject.parse_input(params) expect(params.key?(:string_field)).to be false end end end context 'with treat_empty_as_nil being false' do before do RailsAdmin.config FieldTest do field :string_field do treat_empty_as_nil false end end end let(:params) { {string_field: ''} } it 'keeps the value untouched' do subject.parse_input(params) expect(params.key?(:string_field)).to be true expect(params[:string_field]).to eq '' end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/carrierwave_spec.rb
spec/rails_admin/config/fields/types/carrierwave_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Carrierwave do it_behaves_like 'a generic field type', :string_field, :carrierwave describe '#thumb_method' do before do RailsAdmin.config FieldTest do field :carrierwave_asset, :carrierwave end end let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :carrierwave_asset end.with( object: FieldTest.new(string_field: 'dummy.txt'), view: ApplicationController.new.view_context, ) end it 'auto-detects thumb-like version name' do expect(rails_admin_field.thumb_method).to eq :thumb end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/file_upload_spec.rb
spec/rails_admin/config/fields/types/file_upload_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::FileUpload do it_behaves_like 'a generic field type', :string_field, :file_upload describe '#allowed_methods' do it 'includes delete_method and cache_method' do RailsAdmin.config do |config| config.model FieldTest do field :carrierwave_asset field :dragonfly_asset field :paperclip_asset do delete_method :delete_paperclip_asset end if defined?(ActiveStorage) field :active_storage_asset do delete_method :remove_active_storage_asset end end if defined?(Shrine) field :shrine_asset do delete_method :remove_shrine_asset cache_method :cached_shrine_asset_data end end end end expect(RailsAdmin.config(FieldTest).field(:carrierwave_asset).allowed_methods.collect(&:to_s)).to eq %w[carrierwave_asset remove_carrierwave_asset carrierwave_asset_cache] expect(RailsAdmin.config(FieldTest).field(:dragonfly_asset).allowed_methods.collect(&:to_s)).to eq %w[dragonfly_asset remove_dragonfly_asset retained_dragonfly_asset] expect(RailsAdmin.config(FieldTest).field(:paperclip_asset).allowed_methods.collect(&:to_s)).to eq %w[paperclip_asset delete_paperclip_asset] expect(RailsAdmin.config(FieldTest).field(:active_storage_asset).allowed_methods.collect(&:to_s)).to eq %w[active_storage_asset remove_active_storage_asset] if defined?(ActiveStorage) expect(RailsAdmin.config(FieldTest).field(:shrine_asset).allowed_methods.collect(&:to_s)).to eq %w[shrine_asset remove_shrine_asset cached_shrine_asset_data] if defined?(Shrine) end end describe '#html_attributes' do context 'when the field is required and value is already set' do before do RailsAdmin.config FieldTest do field :string_field, :file_upload do required true end end end let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with(object: FieldTest.new(string_field: 'dummy.jpg')) end it 'does not have a required attribute' do expect(rails_admin_field.html_attributes[:required]).to be_falsy end end end describe '#pretty_value' do context 'when the field is not image' do before do RailsAdmin.config FieldTest do field :string_field, :file_upload do def resource_url 'http://example.com/dummy.txt' end end end end let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with( object: FieldTest.new(string_field: 'dummy.txt'), view: ApplicationController.new.view_context, ) end it 'uses filename as link text' do expect(Nokogiri::HTML(rails_admin_field.pretty_value).text).to eq 'dummy.txt' end end end describe '#image?' do let(:filename) { 'dummy.txt' } let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with( object: FieldTest.new(string_field: filename), view: ApplicationController.new.view_context, ) end before do RailsAdmin.config FieldTest do field :string_field, :file_upload do def resource_url "http://example.com/#{value}" end end end end context 'when the file is not an image' do let(:filename) { 'dummy.txt' } it 'returns false' do expect(rails_admin_field.image?).to be false end end context 'when the file is an image' do let(:filename) { 'dummy.jpg' } it 'returns true' do expect(rails_admin_field.image?).to be true end end context 'when the file is an image but suffixed with a query string' do let(:filename) { 'dummy.jpg?foo=bar' } it 'returns true' do expect(rails_admin_field.image?).to be true end end context "when the filename can't be represented as a valid URI" do let(:filename) { 'du mmy.jpg' } it 'returns false' do expect(rails_admin_field.image?).to be false end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/has_one_association_spec.rb
spec/rails_admin/config/fields/types/has_one_association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::HasOneAssociation do it_behaves_like 'a generic field type', :integer_field, :has_one_association end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/timestamp_spec.rb
spec/rails_admin/config/fields/types/timestamp_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Timestamp, active_record: true do it_behaves_like 'a generic field type', :timestamp_field, :timestamp describe '#parse_input' do before :each do @object = FactoryBot.create(:field_test) @time = ::Time.now.getutc @field = RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :timestamp_field } end after :each do Time.zone = 'UTC' end it 'reads %B %d, %Y %H:%M' do @object.timestamp_field = @field.parse_input(timestamp_field: @time.strftime('%B %d, %Y %H:%M')) expect(@object.timestamp_field.strftime('%Y-%m-%d %H:%M')).to eq(@time.strftime('%Y-%m-%d %H:%M')) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/paperclip_spec.rb
spec/rails_admin/config/fields/types/paperclip_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Paperclip do it_behaves_like 'a generic field type', :string_field, :paperclip context 'when a *_file_name field exists but not declared as has_attached_file' do before do class PaperclipTest < Tableless column :some_file_name, :varchar end RailsAdmin.config.included_models = [PaperclipTest] end it 'does not break' do expect { RailsAdmin.config(PaperclipTest).fields }.not_to raise_error end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/enum_spec.rb
spec/rails_admin/config/fields/types/enum_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Enum do it_behaves_like 'a generic field type', :string_field, :enum subject { RailsAdmin.config(Team).field(:color) } describe "when object responds to '\#{method}_enum'" do before do allow_any_instance_of(Team).to receive(:color_enum).and_return(%w[blue green red]) RailsAdmin.config Team do edit do field :color end end end it 'auto-detects enumeration' do is_expected.to be_a(RailsAdmin::Config::Fields::Types::Enum) is_expected.not_to be_multiple expect(subject.with(object: Team.new).enum).to eq %w[blue green red] end end describe "when class responds to '\#{method}_enum'" do before do allow(Team).to receive(:color_enum).and_return(%w[blue green red]) Team.instance_eval do def color_enum %w[blue green red] end end RailsAdmin.config Team do edit do field :color end end end it 'auto-detects enumeration' do is_expected.to be_a(RailsAdmin::Config::Fields::Types::Enum) expect(subject.with(object: Team.new).enum).to eq %w[blue green red] end end describe 'the enum instance method' do before do Team.class_eval do def color_list %w[blue green red] end end RailsAdmin.config Team do field :color, :enum do enum_method :color_list end end end after do Team.send(:remove_method, :color_list) end it 'allows configuration' do is_expected.to be_a(RailsAdmin::Config::Fields::Types::Enum) expect(subject.with(object: Team.new).enum).to eq %w[blue green red] end end describe 'the enum class method' do before do Team.instance_eval do def color_list %w[blue green red] end end RailsAdmin.config Team do field :color, :enum do enum_method :color_list end end end after do Team.instance_eval { undef :color_list } end it 'allows configuration' do is_expected.to be_a(RailsAdmin::Config::Fields::Types::Enum) expect(subject.with(object: Team.new).enum).to eq %w[blue green red] end end describe 'when overriding enum configuration' do before do Team.class_eval do def color_list %w[blue green red] end end RailsAdmin.config Team do field :color, :enum do enum_method :color_list enum do %w[yellow black] end end end end after do Team.send(:remove_method, :color_list) end it 'allows direct listing of enumeration options and override enum method' do is_expected.to be_a(RailsAdmin::Config::Fields::Types::Enum) expect(subject.with(object: Team.new).enum).to eq %w[yellow black] end end describe 'when serialize is enabled in ActiveRecord model', active_record: true do subject { RailsAdmin.config(TeamWithSerializedEnum).field(:color) } before do class TeamWithSerializedEnum < Team self.table_name = 'teams' if ActiveRecord.gem_version < Gem::Version.new('7.1') serialize :color else serialize :color, coder: JSON end def color_enum %w[blue green red] end end RailsAdmin.config do |c| c.included_models = [TeamWithSerializedEnum] end end it 'makes enumeration multi-selectable' do is_expected.to be_multiple end end describe 'when serialize is enabled in Mongoid model', mongoid: true do before do allow(Team).to receive(:color_enum).and_return(%w[blue green red]) Team.instance_eval do field :color, type: Array end end after do Team.instance_eval do field :color, type: String end end it 'makes enumeration multi-selectable' do is_expected.to be_multiple end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/active_storage_spec.rb
spec/rails_admin/config/fields/types/active_storage_spec.rb
# frozen_string_literal: true require 'spec_helper' if defined?(ActiveStorage) RSpec.describe RailsAdmin::Config::Fields::Types::ActiveStorage do it_behaves_like 'a generic field type', :string_field, :active_storage let(:record) { FactoryBot.create :field_test } let(:field) do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :active_storage_asset end.with(object: record) end describe '#thumb_method' do it 'returns corresponding value which is to be passed to image_processing(ActiveStorage >= 6.0) or mini_magick(ActiveStorage 5.2)' do expect(field.thumb_method).to eq(resize_to_limit: [100, 100]) end end describe '#image?' do context 'configured Mime::Types' do before { Mime::Type.register 'image/webp', :webp } after { Mime::Type.unregister :webp } %w[jpg jpeg png gif svg webp].each do |image_type_ext| context "when attachment is a '#{image_type_ext}' file" do let(:record) { FactoryBot.create :field_test, active_storage_asset: {io: StringIO.new('dummy'), filename: "test.#{image_type_ext}"} } it 'returns true' do expect(field.image?).to be_truthy end end end end context 'when attachment is not an image' do let(:record) { FactoryBot.create :field_test, active_storage_asset: {io: StringIO.new('dummy'), filename: 'test.txt', content_type: 'text/plain'} } it 'returns false' do expect(field.image?).to be_falsy end end context 'when attachment is a PDF file' do let(:record) { FactoryBot.create :field_test, active_storage_asset: {io: StringIO.new('dummy'), filename: 'test.pdf', content_type: 'application/pdf'} } before { allow(ActiveStorage::Previewer::PopplerPDFPreviewer).to receive(:accept?).and_return(true) } it 'returns true' do expect(field.image?).to be_truthy end end end describe '#resource_url' do context 'when calling with thumb = false' do let(:record) { FactoryBot.create :field_test, active_storage_asset: {io: StringIO.new('dummy'), filename: 'test.jpg', content_type: 'image/jpeg'} } it 'returns original url' do expect(field.resource_url).not_to match(/representations/) end end context 'when attachment is an image' do let(:record) { FactoryBot.create :field_test, active_storage_asset: {io: StringIO.new('dummy'), filename: 'test.jpg', content_type: 'image/jpeg'} } it 'returns variant\'s url' do expect(field.resource_url(true)).to match(/representations/) end end context 'when attachment is not an image' do let(:record) { FactoryBot.create :field_test, active_storage_asset: {io: StringIO.new('dummy'), filename: 'test.txt', content_type: 'text/plain'} } it 'returns original url' do expect(field.resource_url(true)).not_to match(/representations/) end end context 'when attachment is a PDF file' do let(:record) { FactoryBot.create :field_test, active_storage_asset: {io: StringIO.new('dummy'), filename: 'test.pdf', content_type: 'application/pdf'} } before { allow(ActiveStorage::Previewer::PopplerPDFPreviewer).to receive(:accept?).and_return(true) } it 'returns variant\'s url' do expect(field.resource_url(true)).to match(/representations/) end end end describe '#value' do context 'when attachment exists' do let(:record) { FactoryBot.create :field_test, active_storage_asset: {io: StringIO.new('dummy'), filename: 'test.jpg', content_type: 'image/jpeg'} } it 'returns attached object' do expect(field.value).to be_a(ActiveStorage::Attached::One) end end context 'when attachment does not exist' do let(:record) { FactoryBot.create :field_test } it 'returns nil' do expect(field.value).to be_nil end end end describe '#eager_load' do it 'points to associations to be eager-loaded' do expect(field.eager_load).to eq({active_storage_asset_attachment: :blob}) end end describe '#direct' do let(:view) { double } let(:field) do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :active_storage_asset end.with(view: view) end before do allow(view).to receive_message_chain(:main_app, :rails_direct_uploads_url) { 'http://www.example.com/rails/active_storage/direct_uploads' } end context 'when false' do it "doesn't put the direct upload url in html_attributes" do expect(field.html_attributes[:data]&.[](:direct_upload_url)).to be_nil end end context 'when true' do before do RailsAdmin.config FieldTest do field(:active_storage_asset) { direct true } end end it 'puts the direct upload url in html_attributes' do expect(field.html_attributes[:data]&.[](:direct_upload_url)).to eq 'http://www.example.com/rails/active_storage/direct_uploads' end end end describe '#searchable' do it 'is false' do expect(field.searchable).to be false end end describe '#sortable' do it 'is false' do expect(field.sortable).to be false end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/datetime_spec.rb
spec/rails_admin/config/fields/types/datetime_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Datetime do it_behaves_like 'a generic field type', :datetime_field, :datetime describe '#formatted_value' do it 'gets object value' do field = RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :datetime_field end.with(object: FieldTest.new(datetime_field: DateTime.parse('02/01/2012'))) expect(field.formatted_value).to eq 'January 02, 2012 00:00' end it 'gets default value for new objects if value is nil' do RailsAdmin.config(FieldTest) do |_config| field :datetime_field do default_value DateTime.parse('01/01/2012') end end field = RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :datetime_field end.with(object: FieldTest.new) expect(field.formatted_value).to eq 'January 01, 2012 00:00' end end describe '#parse_input' do let(:field) { RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :datetime_field } } before :each do @object = FactoryBot.create(:field_test) @time = ::Time.now.getutc end after :each do Time.zone = 'UTC' end it 'is able to read %B %-d, %Y %H:%M' do @object = FactoryBot.create(:field_test) @object.datetime_field = field.parse_input(datetime_field: @time.strftime('%B %-d, %Y %H:%M')) expect(@object.datetime_field.strftime('%Y-%m-%d %H:%M')).to eq(@time.strftime('%Y-%m-%d %H:%M')) end it 'is able to read %a, %d %b %Y %H:%M:%S %z' do RailsAdmin.config FieldTest do field :datetime_field do date_format do :default end end end @object = FactoryBot.create(:field_test) @object.datetime_field = field.parse_input(datetime_field: @time.strftime('%a, %d %b %Y %H:%M:%S %z')) expect(@object.datetime_field.to_formatted_s(:rfc822)).to eq(@time.to_formatted_s(:rfc822)) end it 'has a customization option' do RailsAdmin.config FieldTest do field :datetime_field do strftime_format do '%Y-%m-%d %H:%M:%S' end end end @object = FactoryBot.create(:field_test) @object.datetime_field = field.parse_input(datetime_field: @time.strftime('%Y-%m-%d %H:%M:%S')) expect(@object.datetime_field.to_formatted_s(:rfc822)).to eq(@time.to_formatted_s(:rfc822)) end it 'does round-trip saving properly with non-UTC timezones' do RailsAdmin.config FieldTest do field :datetime_field do date_format do :default end end end Time.zone = 'Vienna' @object = FactoryBot.create(:field_test) @object.datetime_field = field.parse_input(datetime_field: 'Sat, 01 Sep 2012 12:00:00 +0200') expect(@object.datetime_field).to eq(Time.zone.parse('2012-09-01 12:00:00 +02:00')) end it 'changes formats when the locale changes' do french_format = '%A %d %B %Y %H:%M' allow(I18n).to receive(:t).with(:long, scope: %i[time formats], raise: true).and_return(french_format) @object = FactoryBot.create(:field_test) @object.datetime_field = field.parse_input(datetime_field: @time.strftime(french_format)) expect(@object.datetime_field.strftime(french_format)).to eq(@time.strftime(french_format)) american_format = '%B %d, %Y %H:%M' allow(I18n).to receive(:t).with(:long, scope: %i[time formats], raise: true).and_return(american_format) @object = FactoryBot.create(:field_test) @object.datetime_field = field.parse_input(datetime_field: @time.strftime(american_format)) expect(@object.datetime_field.strftime(american_format)).to eq(@time.strftime(american_format)) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/inet_spec.rb
spec/rails_admin/config/fields/types/inet_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Inet do it_behaves_like 'a generic field type', :string_field, :inet end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/hidden_spec.rb
spec/rails_admin/config/fields/types/hidden_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Hidden do it_behaves_like 'a generic field type', :integer_field, :hidden it_behaves_like 'a string-like field type', :string_field, :hidden end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/drangonfly_spec.rb
spec/rails_admin/config/fields/types/drangonfly_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Dragonfly do it_behaves_like 'a generic field type', :string_field, :dragonfly let(:field) do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :dragonfly_asset end.with(object: record) end describe '#image?' do let(:file) { File.open(file_path('test.jpg')) } let(:record) { FactoryBot.create :field_test, dragonfly_asset: file } it 'returns true' do expect(field.image?).to be true end context 'with non-image' do let(:file) { File.open(file_path('test.txt')) } it 'returns false' do expect(field.image?).to be false end end end describe 'with a model which does not extend Dragonfly::Model' do before do class NonDragonflyTest < Tableless column :asset_uid, :varchar end end it 'does not break' do expect { RailsAdmin.config(NonDragonflyTest).fields }.not_to raise_error end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/has_and_belongs_to_many_association_spec.rb
spec/rails_admin/config/fields/types/has_and_belongs_to_many_association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::HasAndBelongsToManyAssociation do it_behaves_like 'a generic field type', :integer_field, :has_and_belongs_to_many_association end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/multiple_carrierwave_spec.rb
spec/rails_admin/config/fields/types/multiple_carrierwave_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'base64' RSpec.describe RailsAdmin::Config::Fields::Types::MultipleCarrierwave do it_behaves_like 'a generic field type', :string_field, :multiple_carrierwave describe '#thumb_method' do before do RailsAdmin.config FieldTest do field :carrierwave_assets, :multiple_carrierwave end end let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :carrierwave_assets end.with( object: FieldTest.new(carrierwave_assets: [File.open(file_path('test.jpg'))]), view: ApplicationController.new.view_context, ) end it 'auto-detects thumb-like version name' do expect(rails_admin_field.attachments.map(&:thumb_method)).to eq [:thumb] end end describe '#delete_value', active_record: true do before do RailsAdmin.config FieldTest do field :carrierwave_assets, :multiple_carrierwave end end let :file do CarrierWave::SanitizedFile.new( tempfile: StringIO.new(Base64.decode64('R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=')), filename: 'dummy.gif', ) end let :rails_admin_field do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :carrierwave_assets end.with( object: FieldTest.create(carrierwave_assets: [file]), view: ApplicationController.new.view_context, ) end it 'does not use file.identifier, which is not available for Fog files' do expect_any_instance_of(CarrierWave::SanitizedFile).not_to receive :identifier expect(rails_admin_field.attachments.map(&:delete_value)).to eq ['dummy.gif'] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/serialized_spec.rb
spec/rails_admin/config/fields/types/serialized_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Serialized do it_behaves_like 'a generic field type', :text_field, :serialized end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/has_many_association_spec.rb
spec/rails_admin/config/fields/types/has_many_association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::HasManyAssociation do it_behaves_like 'a generic field type', :integer_field, :has_many_association end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/numeric_spec.rb
spec/rails_admin/config/fields/types/numeric_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Numeric do it_behaves_like 'a generic field type', :integer_field, :integer subject do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :integer_field end.with(object: FieldTest.new) end describe '#view_helper' do it "uses the 'number' type input tag" do expect(subject.view_helper).to eq(:number_field) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/password_spec.rb
spec/rails_admin/config/fields/types/password_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Password do it_behaves_like 'a generic field type', :string_field, :password describe '#parse_input' do let(:field) do RailsAdmin.config(User).fields.detect do |f| f.name == :password end end context 'if password is not present' do let(:nil_params) { {password: nil} } let(:blank_params) { {password: ''} } it 'cleans nil' do field.parse_input(nil_params) expect(nil_params).to eq({}) field.parse_input(blank_params) expect(blank_params).to eq({}) end end context 'if password is present' do let(:params) { {password: 'aaa'} } it 'keeps the value' do field.parse_input(params) expect(params).to eq(password: 'aaa') end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/ck_editor_spec.rb
spec/rails_admin/config/fields/types/ck_editor_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::CKEditor do it_behaves_like 'a generic field type', :text_field, :ck_editor it_behaves_like 'a string-like field type', :text_field, :ck_editor end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/action_text_spec.rb
spec/rails_admin/config/fields/types/action_text_spec.rb
# frozen_string_literal: true require 'spec_helper' if defined?(ActionText) RSpec.describe RailsAdmin::Config::Fields::Types::ActionText do it_behaves_like 'a generic field type', :action_text_field it_behaves_like 'a string-like field type', :action_text_field end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/shrine_spec.rb
spec/rails_admin/config/fields/types/shrine_spec.rb
# frozen_string_literal: true require 'spec_helper' if defined?(Shrine) RSpec.describe RailsAdmin::Config::Fields::Types::Shrine do context 'when asset is an image with versions' do let(:record) { FactoryBot.create :field_test, shrine_versioning_asset: FakeIO.new('dummy', filename: 'test.jpg', content_type: 'image/jpeg') } let(:field) do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :shrine_versioning_asset end.with(object: record) end before do if Gem.loaded_specs['shrine'].version >= Gem::Version.create('3') if record.shrine_versioning_asset record.shrine_versioning_asset_derivatives! record.save end else skip end end describe '#image?' do it 'returns true' do expect(field.image?).to be_truthy end end describe '#link_name' do it 'returns filename' do expect(field.link_name).to eq('test.jpg') end end describe '#value' do context 'when attachment exists' do it 'returns attached object' do expect(field.value).to be_a(ShrineVersioningUploader::UploadedFile) end end context 'when attachment does not exist' do let(:record) { FactoryBot.create :field_test } it 'returns nil' do expect(field.value).to be_nil end end end describe '#thumb_method' do it 'returns :thumb' do expect(field.thumb_method).to eq(:thumb) end end describe '#resource_url' do context 'when calling without thumb' do it 'returns original url' do expect(field.resource_url).to_not match(/thumb-/) end end context 'when calling with thumb' do it 'returns thumb url' do expect(field.resource_url(field.thumb_method)).to match(/thumb-/) end end end end context 'when asset without versions' do let(:record) { FactoryBot.create :field_test } let(:field) do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :shrine_asset end.with(object: record) end describe '#image?' do context 'when attachment is an image' do let(:record) { FactoryBot.create :field_test, shrine_asset: FakeIO.new('dummy', filename: 'test.jpg', content_type: 'image/jpeg') } it 'returns true' do expect(field.image?).to be_truthy end end context 'when attachment is not an image' do let(:record) { FactoryBot.create :field_test, shrine_asset: FakeIO.new('dummy', filename: 'test.txt', content_type: 'text/plain') } it 'returns false' do expect(field.image?).to be_falsy end end end describe '#value' do context 'when attachment exists' do let(:record) { FactoryBot.create :field_test, shrine_asset: FakeIO.new('dummy', filename: 'test.txt', content_type: 'text/plain') } it 'returns attached object' do expect(field.value).to be_a(ShrineUploader::UploadedFile) end end context 'when attachment does not exist' do it 'returns nil' do expect(field.value).to be_nil end end end describe '#thumb_method' do let(:record) { FactoryBot.create :field_test, shrine_asset: FakeIO.new('dummy', filename: 'test.jpg', content_type: 'image/jpeg') } it 'returns nil' do expect(field.thumb_method).to eq(nil) end end describe '#resource_url' do context 'when calling without thumb' do let(:record) { FactoryBot.create :field_test, shrine_asset: FakeIO.new('dummy', filename: 'test.txt', content_type: 'text/plain') } it 'returns url' do expect(field.resource_url).not_to be_nil end end context 'when calling with thumb' do let(:record) { FactoryBot.create :field_test, shrine_asset: FakeIO.new('dummy', filename: 'test.jpg', content_type: 'image/jpeg') } it 'returns url' do expect(field.resource_url(field.thumb_method)).not_to be_nil end end context 'when attachment does not exist' do it 'returns nil' do expect(field.resource_url).to be_nil end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/multiple_active_storage_spec.rb
spec/rails_admin/config/fields/types/multiple_active_storage_spec.rb
# frozen_string_literal: true require 'spec_helper' if defined?(ActiveStorage) RSpec.describe RailsAdmin::Config::Fields::Types::MultipleActiveStorage do it_behaves_like 'a generic field type', :string_field, :multiple_active_storage let(:record) { FactoryBot.create :field_test } let(:field) do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :active_storage_assets end.with( object: record, view: ApplicationController.new.view_context, ) end describe RailsAdmin::Config::Fields::Types::MultipleActiveStorage::ActiveStorageAttachment do describe '#thumb_method' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.txt', content_type: 'text/plain'}] } subject { field.attachments[0] } it 'returns corresponding value which is to be passed to image_processing(ActiveStorage >= 6.0) or mini_magick(ActiveStorage 5.2)' do expect(subject.thumb_method).to eq(resize_to_limit: [100, 100]) end end describe '#pretty_value' do subject { field.pretty_value } context 'when attachment is not an image' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.txt', content_type: 'text/plain'}] } it 'uses filename as link text' do expect(Nokogiri::HTML(subject).text).to eq 'test.txt' end end context 'when the field is an image' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.jpg', content_type: 'image/jpeg'}] } it 'shows thumbnail image with a link' do expect(Nokogiri::HTML(subject).css('img').attribute('src').value).to match(%r{rails/active_storage/representations}) expect(Nokogiri::HTML(subject).css('a').attribute('href').value).to match(%r{rails/active_storage/blobs}) end end end describe '#image?' do context 'when attachment is an image' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.jpg', content_type: 'image/jpeg'}] } it 'returns true' do expect(field.attachments[0].image?).to be_truthy end end context 'when attachment is not an image' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.txt', content_type: 'text/plain'}] } it 'returns false' do expect(field.attachments[0].image?).to be_falsy end end context 'when attachment is a PDF file' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.pdf', content_type: 'application/pdf'}] } before { allow(ActiveStorage::Previewer::PopplerPDFPreviewer).to receive(:accept?).and_return(true) } it 'returns true' do expect(field.attachments[0].image?).to be_truthy end end end describe '#resource_url' do context 'when calling with thumb = false' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.jpg', content_type: 'image/jpeg'}] } it 'returns original url' do expect(field.attachments[0].resource_url).not_to match(/representations/) end end context 'when attachment is an image' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.jpg', content_type: 'image/jpeg'}] } it 'returns variant\'s url' do expect(field.attachments[0].resource_url(true)).to match(/representations/) end end context 'when attachment is not an image' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.txt', content_type: 'text/plain'}] } it 'returns original url' do expect(field.attachments[0].resource_url(true)).not_to match(/representations/) end end context 'when attachment is a PDF file' do let(:record) { FactoryBot.create :field_test, active_storage_assets: [{io: StringIO.new('dummy'), filename: 'test.pdf', content_type: 'application/pdf'}] } before { allow(ActiveStorage::Previewer::PopplerPDFPreviewer).to receive(:accept?).and_return(true) } it 'returns variant\'s url' do expect(field.attachments[0].resource_url(true)).to match(/representations/) end end end end describe '#eager_load' do it 'points to associations to be eager-loaded' do expect(field.eager_load).to eq({active_storage_assets_attachments: :blob}) end end describe '#direct' do let(:view) { double } let(:field) do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :active_storage_assets end.with(view: view) end before do allow(view).to receive_message_chain(:main_app, :rails_direct_uploads_url) { 'http://www.example.com/rails/active_storage/direct_uploads' } end context 'when false' do it "doesn't put the direct upload url in html_attributes" do expect(field.html_attributes[:data]&.[](:direct_upload_url)).to be_nil end end context 'when true' do before do RailsAdmin.config FieldTest do field(:active_storage_assets) { direct true } end end it 'puts the direct upload url in html_attributes' do expect(field.html_attributes[:data]&.[](:direct_upload_url)).to eq 'http://www.example.com/rails/active_storage/direct_uploads' end end end describe '#searchable' do it 'is false' do expect(field.searchable).to be false end end describe '#sortable' do it 'is false' do expect(field.sortable).to be false end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/decimal_spec.rb
spec/rails_admin/config/fields/types/decimal_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Decimal do it_behaves_like 'a float-like field type', :float_field end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/wysihtml5_spec.rb
spec/rails_admin/config/fields/types/wysihtml5_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Wysihtml5 do it_behaves_like 'a generic field type', :text_field, :wysihtml5 it_behaves_like 'a string-like field type', :text_field, :wysihtml5 end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/color_spec.rb
spec/rails_admin/config/fields/types/color_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Color do it_behaves_like 'a generic field type', :string_field, :color it_behaves_like 'a string-like field type', :string_field, :color end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/citext_spec.rb
spec/rails_admin/config/fields/types/citext_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Citext do it_behaves_like 'a generic field type', :string_field it_behaves_like 'a string-like field type', :string_field end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/json_spec.rb
spec/rails_admin/config/fields/types/json_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Json do let(:field) { RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :json_field } } let(:object) { FieldTest.new } let(:bindings) do { object: object, view: ApplicationController.new.view_context, } end describe '#formatted_value' do before do RailsAdmin.config do |config| config.model FieldTest do field :json_field, :json end end end it 'returns correct value for empty json' do allow(object).to receive(:json_field) { {} } actual = field.with(bindings).formatted_value expect(actual).to match(/{\n*}/) end it 'retuns correct value' do allow(object).to receive(:json_field) { {sample_key: 'sample_value'} } actual = field.with(bindings).formatted_value expected = [ '{', ' "sample_key": "sample_value"', '}', ].join("\n") expect(actual).to eq(expected) end end describe '#pretty_value' do before do RailsAdmin.config do |config| config.model FieldTest do field :json_field, :json end end end it 'retuns correct value' do allow(object).to receive(:json_field) { {sample_key: 'sample_value'} } actual = field.with(bindings).pretty_value expected = [ '<pre>{', ' &quot;sample_key&quot;: &quot;sample_value&quot;', '}</pre>', ].join("\n") expect(actual).to eq(expected) end end describe '#export_value' do before do RailsAdmin.config do |config| config.model FieldTest do field :json_field, :json end end end it 'returns correct value for empty json' do allow(object).to receive(:json_field) { {} } actual = field.with(bindings).export_value expect(actual).to match(/{\n*}/) end it 'returns correct value' do allow(object).to receive(:json_field) { {sample_key: 'sample_value'} } actual = field.with(bindings).export_value expected = [ '{', ' "sample_key": "sample_value"', '}', ].join("\n") expect(actual).to eq(expected) end end describe '#parse_input' do before :each do RailsAdmin.config do |config| config.model FieldTest do field :json_field, :json end end end it 'parse valid json string' do data = {string: 'string', integer: 1, array: [1, 2, 3], object: {bla: 'foo'}}.as_json expect(field.parse_input(json_field: data.to_json)).to eq data end it 'raise JSON::ParserError with invalid json string' do expect { field.parse_input(json_field: '{{') }.to raise_error(JSON::ParserError) end end describe 'aliasing' do before :each do RailsAdmin.config do |config| config.model FieldTest do field :json_field, :jsonb end end end it 'allows use of :jsonb fieldtype' do expect(field.class).to eq RailsAdmin::Config::Fields::Types::Json end end it_behaves_like 'a generic field type', :text, :json end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/active_record_enum_spec.rb
spec/rails_admin/config/fields/types/active_record_enum_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::ActiveRecordEnum, active_record: true do it_behaves_like 'a generic field type', :string_enum_field describe '#pretty_value' do context 'when column name is format' do before do class FormatAsEnum < FieldTest if ActiveRecord.gem_version >= Gem::Version.new('7.0') enum :format, {Text: 'txt', Markdown: 'md'} else enum format: {Text: 'txt', Markdown: 'md'} end end end let(:field) do RailsAdmin.config(FormatAsEnum).fields.detect do |f| f.name == :format end.with(object: FormatAsEnum.new(format: 'md')) end it 'does not break' do expect(field.pretty_value).to eq 'Markdown' end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/time_spec.rb
spec/rails_admin/config/fields/types/time_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Time, active_record: true do it_behaves_like 'a generic field type', :time_field, :time describe '#parse_input' do let(:field) do RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :time_field end end before do RailsAdmin.config(FieldTest) do field :time_field, :time end end before :each do @object = FactoryBot.create(:field_test) @time = ::Time.new(2000, 1, 1, 3, 45) end after :each do Time.zone = 'UTC' end it 'reads %H:%M' do @object.time_field = field.parse_input(time_field: @time.strftime('%H:%M')) expect(@object.time_field.strftime('%H:%M')).to eq(@time.strftime('%H:%M')) end it 'interprets time value as local time when timezone is specified' do Time.zone = 'Eastern Time (US & Canada)' # -05:00 @object.time_field = field.parse_input(time_field: '2000-01-01T03:45:00') expect(@object.time_field.strftime('%H:%M')).to eq('03:45') end context 'with a custom strftime_format' do let(:field) do RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :time_field end end before do RailsAdmin.config(FieldTest) do field :time_field, :time do strftime_format '%I:%M %p' end end end it 'has a customization option' do @object.time_field = field.parse_input(time_field: @time.strftime('%I:%M %p')) expect(@object.time_field.strftime('%H:%M')).to eq(@time.strftime('%H:%M')) end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/float_spec.rb
spec/rails_admin/config/fields/types/float_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Float do it_behaves_like 'a float-like field type', :float_field end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/belongs_to_association_spec.rb
spec/rails_admin/config/fields/types/belongs_to_association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::BelongsToAssociation do it_behaves_like 'a generic field type', :integer_field, :belongs_to_association end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/boolean_spec.rb
spec/rails_admin/config/fields/types/boolean_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Boolean do it_behaves_like 'a generic field type', :boolean_field, :boolean subject do RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :boolean_field end.with(object: test_object) end describe '#pretty_value' do { false => %(<span class="badge bg-danger"><span class="fas fa-times"></span></span>), true => %(<span class="badge bg-success"><span class="fas fa-check"></span></span>), nil => %(<span class="badge bg-default"><span class="fas fa-minus"></span></span>), }.each do |field_value, expected_result| context "when field value is '#{field_value.inspect}'" do let(:test_object) { FieldTest.new(boolean_field: field_value) } it 'returns the appropriate html result' do expect(subject.pretty_value).to eq(expected_result) end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/simple_mde_spec.rb
spec/rails_admin/config/fields/types/simple_mde_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::SimpleMDE do it_behaves_like 'a generic field type', :text_field, :simple_mde it_behaves_like 'a string-like field type', :text_field, :simple_mde end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/froala_spec.rb
spec/rails_admin/config/fields/types/froala_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Froala do it_behaves_like 'a generic field type', :text_field, :froala it_behaves_like 'a string-like field type', :text_field, :froala end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/date_spec.rb
spec/rails_admin/config/fields/types/date_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Date do it_behaves_like 'a generic field type', :date_field, :date describe '#formatted_value' do it 'gets object value' do field = RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :date_field end.with(object: FieldTest.new(date_field: DateTime.parse('02/01/2012'))) expect(field.formatted_value).to eq 'January 02, 2012' end it 'gets default value for new objects if value is nil' do RailsAdmin.config(FieldTest) do |_config| field :date_field do default_value DateTime.parse('01/01/2012') end end field = RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :date_field end.with(object: FieldTest.new) expect(field.formatted_value).to eq 'January 01, 2012' end end describe '#parse_input' do let(:field) { RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :date_field } } before :each do @object = FactoryBot.create(:field_test) @time = ::Time.now.getutc end after :each do Time.zone = 'UTC' end it 'reads %B %d, %Y by default' do @object.date_field = field.parse_input(date_field: @time.strftime('%B %d, %Y')) expect(@object.date_field).to eq(::Date.parse(@time.to_s)) end it 'covers a timezone lag even if in UTC+n:00 timezone.' do Time.zone = 'Tokyo' # +09:00 @object.date_field = field.parse_input(date_field: @time.strftime('%B %d, %Y')) expect(@object.date_field).to eq(::Date.parse(@time.to_s)) end it 'has a simple customization option' do RailsAdmin.config FieldTest do field :date_field do date_format do :default end end end @object.date_field = field.parse_input(date_field: @time.strftime('%Y-%m-%d')) expect(@object.date_field).to eq(::Date.parse(@time.to_s)) end it 'has a customization option' do RailsAdmin.config FieldTest do field :date_field do strftime_format '%Y/%m/%d' end end @object.date_field = field.parse_input(date_field: @time.strftime('%Y/%m/%d')) expect(@object.date_field).to eq(::Date.parse(@time.to_s)) end end describe '#default_value' do let(:field) do field = RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :date_field } field.bindings = {object: @object} field end before :each do RailsAdmin.config FieldTest do field :date_field do default_value Date.current end end @object = FactoryBot.create(:field_test) @time = ::Time.now.getutc end it 'should contain the default value' do expect(field.default_value).to eq(Date.current) end it 'should propagate to the field formatted_value when the object is a new record' do object = FactoryBot.build(:field_test) field.bindings = {object: object} expect(field.formatted_value).to eq(Date.current.strftime('%B %d, %Y')) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config/fields/types/integer_spec.rb
spec/rails_admin/config/fields/types/integer_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::Integer do it_behaves_like 'a generic field type', :integer_field, :integer end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/shared_examples/shared_examples_for_field_types.rb
spec/shared_examples/shared_examples_for_field_types.rb
# frozen_string_literal: true require 'spec_helper' RSpec.shared_examples 'a generic field type' do |column_name, field_type| describe '#html_attributes' do context 'when the field is required' do before do RailsAdmin.config FieldTest do field column_name, field_type do required true end end end subject do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == column_name end.with(object: FieldTest.new) end it 'should contain a required attribute with the string "required" as value' do expect(subject.html_attributes[:required]).to be_truthy end end end end RSpec.shared_examples 'a string-like field type' do |column_name, _| subject do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == column_name end.with(object: FieldTest.new) end it 'is a StringLike field' do expect(subject).to be_a(RailsAdmin::Config::Fields::Types::StringLike) end end RSpec.shared_examples 'a float-like field type' do |column_name| subject do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == column_name end.with(object: FieldTest.new) end describe '#html_attributes' do it 'should contain a step attribute' do expect(subject.html_attributes[:step]).to eq('any') end it 'should contain a falsey required attribute' do expect(subject.html_attributes[:required]).to be_falsey end context 'when the field is required' do before do RailsAdmin.config FieldTest do field column_name, :float do required true end end end it 'should contain a truthy required attribute' do expect(subject.html_attributes[:required]).to be_truthy end end end describe '#view_helper' do it "uses the 'number' type input tag" do expect(subject.view_helper).to eq(:number_field) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/orm/active_record.rb
spec/orm/active_record.rb
# frozen_string_literal: true require 'rails_admin/adapters/active_record' ActiveRecord::Base.connection.data_sources.each do |table| ActiveRecord::Base.connection.drop_table(table) end def silence_stream(stream) old_stream = stream.dup stream.reopen(/mswin|mingw/.match?(RbConfig::CONFIG['host_os']) ? 'NUL:' : '/dev/null') stream.sync = true yield ensure stream.reopen(old_stream) old_stream.close end silence_stream($stdout) do if ActiveRecord::Migrator.respond_to? :migrate ActiveRecord::Migrator.migrate File.expand_path('../dummy_app/db/migrate', __dir__) else ActiveRecord::MigrationContext.new( *([File.expand_path('../dummy_app/db/migrate', __dir__)] + (ActiveRecord::MigrationContext.instance_method(:initialize).arity == 2 ? [ActiveRecord::SchemaMigration] : [])), ).migrate end end class Tableless < ActiveRecord::Base class << self def load_schema # do nothing end def columns @columns ||= [] end def column(name, sql_type = nil, default = nil, null = true) cast_type = connection.send(:lookup_cast_type, sql_type.to_s) define_attribute(name.to_s, cast_type) columns << if ActiveRecord.version > Gem::Version.new('6.0') type_metadata = ActiveRecord::ConnectionAdapters::SqlTypeMetadata.new( sql_type: sql_type.to_s, type: cast_type.type, limit: cast_type.limit, precision: cast_type.precision, scale: cast_type.scale, ) ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, type_metadata, null) else ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, cast_type, sql_type.to_s, null) end end def columns_hash @columns_hash ||= columns.collect { |column| [column.name, column] }.to_h end def column_names @column_names ||= columns.collect(&:name) end def column_defaults @column_defaults ||= columns.collect { |column| [column.name, nil] }.each_with_object({}) do |e, a| a[e[0]] = e[1] a end end def attribute_types @attribute_types ||= columns.collect { |column| [column.name, lookup_attribute_type(column.type)] }.to_h end def table_exists? true end def primary_key 'id' end private def lookup_attribute_type(type) ActiveRecord::Type.lookup({datetime: :time}[type] || type) end end # Override the save method to prevent exceptions. def save(validate = true) validate ? valid? : true end end ## # Column length detection seems to be broken for PostgreSQL. # This is a workaround.. # Refs. https://github.com/rails/rails/commit/b404613c977a5cc31c6748723e903fa5a0709c3b # if defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do def lookup_cast_type(sql_type) oid = execute("SELECT #{quote(sql_type)}::regtype::oid", 'SCHEMA').first['oid'].to_i type_map.lookup(oid, sql_type) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/orm/mongoid.rb
spec/orm/mongoid.rb
# frozen_string_literal: true require 'rails_admin/adapters/mongoid' Paperclip.logger = Logger.new(nil) class Tableless include Mongoid::Document class << self def column(name, sql_type = 'string', default = nil, _null = true) # ignore length sql_type = sql_type.to_s.sub(/\(.*\)/, '').to_sym field(name, type: {integer: Integer, string: String, text: String, date: Date, datetime: DateTime}[sql_type], default: default) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin.rb
lib/rails_admin.rb
# frozen_string_literal: true require 'rails_admin/engine' require 'rails_admin/abstract_model' require 'rails_admin/config' require 'rails_admin/config/const_load_suppressor' require 'rails_admin/extension' require 'rails_admin/extensions/cancancan' require 'rails_admin/extensions/pundit' require 'rails_admin/extensions/paper_trail' require 'rails_admin/support/csv_converter' require 'rails_admin/support/hash_helper' require 'yaml' module RailsAdmin extend RailsAdmin::Config::ConstLoadSuppressor # Setup RailsAdmin # # Given the first argument is a model class, a model class name # or an abstract model object proxies to model configuration method. # # If only a block is passed it is stored to initializer stack to be evaluated # on first request in production mode and on each request in development. If # initialization has already occurred (in other words RailsAdmin.setup has # been called) the block will be added to stack and evaluated at once. # # Otherwise returns RailsAdmin::Config class. # # @see RailsAdmin::Config def self.config(entity = nil, &block) if entity RailsAdmin::Config.model(entity, &block) elsif block_given? RailsAdmin::Config::ConstLoadSuppressor.suppressing { yield(RailsAdmin::Config) } else RailsAdmin::Config end end # Backwards-compatible with safe_yaml/load when SafeYAML isn't available. # Evaluates available YAML loaders at boot and creates appropriate method, # so no conditionals are required at runtime. begin require 'safe_yaml/load' def self.yaml_load(yaml) SafeYAML.load(yaml) end rescue LoadError if YAML.respond_to?(:safe_load) def self.yaml_load(yaml) YAML.safe_load(yaml) end else raise LoadError.new "Safe-loading of YAML is not available. Please install 'safe_yaml' or install Psych 2.0+" end end def self.yaml_dump(object) YAML.dump(object) end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/generators/rails_admin/utils.rb
lib/generators/rails_admin/utils.rb
# frozen_string_literal: true module RailsAdmin module Generators module Utils module InstanceMethods def display(output, color = :green) say(" - #{output}", color) end def ask_for(wording, default_value = nil, override_if_present_value = nil) if override_if_present_value.present? display("Using [#{override_if_present_value}] for question '#{wording}'") && override_if_present_value else ask(" ? #{wording} Press <enter> for [#{default_value}] >", :yellow).presence || default_value end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/generators/rails_admin/importmap_formatter.rb
lib/generators/rails_admin/importmap_formatter.rb
# frozen_string_literal: true require 'importmap/packager' module RailsAdmin class ImportmapFormatter attr_reader :packager def initialize(path = 'config/importmap.rails_admin.rb') @packager = Importmap::Packager.new(path) end def format imports = packager.import("rails_admin@#{RailsAdmin::Version.js}", from: 'jspm.io') imports = imports[:imports] if imports.key?(:imports) # Use ESM compatible version to work around https://github.com/cljsjs/packages/issues/1579 imports['@popperjs/core'].gsub!('lib/index.js', 'dist/esm/popper.js') # Tidy up jQuery UI dependencies jquery_uis = imports.keys.filter { |key, _| key =~ /jquery-ui/ } imports['jquery-ui/'] = imports[jquery_uis.first].gsub(%r{(@[^/@]+)/[^@]+$}, '\1/') imports.reject! { |key, _| jquery_uis.include? key } pins = ['pin "rails_admin", preload: true', packager.pin_for('rails_admin/src/rails_admin/base', imports.delete('rails_admin'))] (pins + imports.map { |package, url| packager.pin_for(package, url) }).join("\n") end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/generators/rails_admin/install_generator.rb
lib/generators/rails_admin/install_generator.rb
# frozen_string_literal: true require 'rails/generators' require 'rails_admin/version' require File.expand_path('utils', __dir__) module RailsAdmin class InstallGenerator < Rails::Generators::Base source_root File.expand_path('templates', __dir__) include Generators::Utils::InstanceMethods argument :_namespace, type: :string, required: false, desc: 'RailsAdmin url namespace' class_option :asset, type: :string, required: false, default: nil, desc: 'Asset delivery method [options: webpacker, webpack, sprockets, importmap, vite]' desc 'RailsAdmin installation generator' def install if File.read(File.join(destination_root, 'config/routes.rb')).include?('mount RailsAdmin::Engine') display "Skipped route addition, since it's already there" else namespace = ask_for('Where do you want to mount rails_admin?', 'admin', _namespace) route("mount RailsAdmin::Engine => '/#{namespace}', as: 'rails_admin'") end if File.exist? File.join(destination_root, 'config/initializers/rails_admin.rb') insert_into_file 'config/initializers/rails_admin.rb', " config.asset_source = :#{asset}\n", after: "RailsAdmin.config do |config|\n" else template 'initializer.erb', 'config/initializers/rails_admin.rb' end display "Using [#{asset}] for asset delivery method" case asset when 'webpack' configure_for_webpack when 'importmap' configure_for_importmap when 'webpacker' configure_for_webpacker5 when 'vite' configure_for_vite when 'sprockets' configure_for_sprockets else raise "Unknown asset source: #{asset}" end end private def asset return options['asset'] if options['asset'] if defined?(Webpacker) 'webpacker' elsif Rails.root.join('webpack.config.js').exist? 'webpack' elsif Rails.root.join('config/importmap.rb').exist? 'importmap' elsif defined?(ViteRuby) 'vite' else 'sprockets' end end def configure_for_sprockets gem 'sassc-rails' end def configure_for_webpacker5 run "yarn add rails_admin@#{RailsAdmin::Version.js}" template 'rails_admin.webpacker.js', 'app/javascript/packs/rails_admin.js' template 'rails_admin.scss.erb', 'app/javascript/stylesheets/rails_admin.scss' # To work around https://github.com/railsadminteam/rails_admin/issues/3565 add_package_json_field('resolutions', {'rails_admin/@fortawesome/fontawesome-free' => '^5.15.0'}) end def configure_for_vite vite_source_code_dir = ViteRuby.config.source_code_dir run "yarn add rails_admin@#{RailsAdmin::Version.js} sass" template('rails_admin.vite.js', File.join(vite_source_code_dir, 'entrypoints', 'rails_admin.js')) @fa_font_path = '@fortawesome/fontawesome-free/webfonts' template('rails_admin.scss.erb', File.join(vite_source_code_dir, 'stylesheets', 'rails_admin.scss')) end def configure_for_webpack run "yarn add rails_admin@#{RailsAdmin::Version.js}" template 'rails_admin.js', 'app/javascript/rails_admin.js' webpack_config = File.join(destination_root, 'webpack.config.js') marker = %r{application: ["']./app/javascript/application.js["']} if File.exist?(webpack_config) && File.read(webpack_config) =~ marker insert_into_file 'webpack.config.js', %(,\n rails_admin: "./app/javascript/rails_admin.js"), after: marker else say 'Add `rails_admin: "./app/javascript/rails_admin.js"` to the entry section in your webpack.config.js.', :red end setup_css({'build' => 'webpack --config webpack.config.js'}) end def configure_for_importmap run "yarn add rails_admin@#{RailsAdmin::Version.js}" template 'rails_admin.js', 'app/javascript/rails_admin.js' require_relative 'importmap_formatter' add_file 'config/importmap.rails_admin.rb', ImportmapFormatter.new.format setup_css end def setup_css(additional_script_entries = {}) gem 'cssbundling-rails' rake 'css:install:sass' @fa_font_path = '.' template 'rails_admin.scss.erb', 'app/assets/stylesheets/rails_admin.scss' asset_config = %{Rails.application.config.assets.paths << Rails.root.join("node_modules/@fortawesome/fontawesome-free/webfonts")\n} if File.exist? File.join(destination_root, 'config/initializers/assets.rb') append_to_file 'config/initializers/assets.rb', asset_config else add_file 'config/initializers/assets.rb', asset_config end add_package_json_field('scripts', additional_script_entries.merge({'build:css' => 'sass ./app/assets/stylesheets/rails_admin.scss:./app/assets/builds/rails_admin.css --no-source-map --load-path=node_modules'}), <<~INSTRUCTION) Taking 'build:css' as an example, if you're already have application.sass.css for the sass build, the resulting script would look like: sass ./app/assets/stylesheets/application.sass.scss:./app/assets/builds/application.css ./app/assets/stylesheets/rails_admin.scss:./app/assets/builds/rails_admin.css --no-source-map --load-path=node_modules INSTRUCTION end def add_package_json_field(name, entries, instruction = nil) display "Add #{name} to package.json" package = begin JSON.parse(File.read(File.join(destination_root, 'package.json'))) rescue Errno::ENOENT, JSON::ParserError {} end if package[name] && (package[name].keys & entries.keys).any? say <<~MESSAGE, :red You need to merge "#{name}": #{JSON.pretty_generate(entries)} into the existing #{name} in your package.json.#{instruction && "\n#{instruction}"} MESSAGE else package[name] ||= {} entries.each do |entry, value| package[name][entry] = value end add_file 'package.json', "#{JSON.pretty_generate(package)}\n" end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/version.rb
lib/rails_admin/version.rb
# frozen_string_literal: true module RailsAdmin class Version MAJOR = 3 MINOR = 3 PATCH = 0 PRE = nil class << self # @return [String] def to_s [MAJOR, MINOR, PATCH, PRE].compact.join('.') end def js JSON.parse(File.read("#{__dir__}/../../package.json"))['version'] end def actual_js_version case RailsAdmin.config.asset_source when :webpacker, :webpack js_version_from_node_modules else js end end def warn_with_js_version return unless Rails.env.development? || Rails.env.test? case actual_js_version when js # Good when nil warn "[Warning] Failed to detect RailsAdmin npm package, did you run 'yarn install'?" else warn <<~MSG [Warning] RailsAdmin npm package version inconsistency detected, expected #{js} but actually used is #{actual_js_version}. This may cause partial or total malfunction of RailsAdmin frontend features. MSG end end private def js_version_from_node_modules JSON.parse(File.read(Rails.root.join('node_modules/rails_admin/package.json')))['version'] rescue StandardError nil end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/config.rb
lib/rails_admin/config.rb
# frozen_string_literal: true require 'rails_admin/config/lazy_model' require 'rails_admin/config/sections/list' require 'rails_admin/support/composite_keys_serializer' require 'active_support/core_ext/module/attribute_accessors' module RailsAdmin module Config # RailsAdmin is setup to try and authenticate with warden # If warden is found, then it will try to authenticate # # This is valid for custom warden setups, and also devise # If you're using the admin setup for devise, you should set RailsAdmin to use the admin # # @see RailsAdmin::Config.authenticate_with # @see RailsAdmin::Config.authorize_with DEFAULT_AUTHENTICATION = proc {} DEFAULT_AUTHORIZE = proc {} DEFAULT_AUDIT = proc {} DEFAULT_CURRENT_USER = proc {} class << self # Application title, can be an array of two elements attr_accessor :main_app_name # Configuration option to specify which models you want to exclude. attr_accessor :excluded_models # Configuration option to specify a allowlist of models you want to RailsAdmin to work with. # The excluded_models list applies against the allowlist as well and further reduces the models # RailsAdmin will use. # If included_models is left empty ([]), then RailsAdmin will automatically use all the models # in your application (less any excluded_models you may have specified). attr_accessor :included_models # Fields to be hidden in show, create and update views attr_reader :default_hidden_fields # Default items per page value used if a model level option has not # been configured attr_accessor :default_items_per_page # Default association limit attr_accessor :default_associated_collection_limit attr_reader :default_search_operator # Configuration option to specify which method names will be searched for # to be used as a label for object records. This defaults to [:name, :title] attr_accessor :label_methods # hide blank fields in show view if true attr_accessor :compact_show_view # Tell browsers whether to use the native HTML5 validations (novalidate form option). attr_accessor :browser_validations # set parent controller attr_reader :parent_controller # set settings for `protect_from_forgery` method # By default, it raises exception upon invalid CSRF tokens attr_accessor :forgery_protection_settings # Stores model configuration objects in a hash identified by model's class # name. # # @see RailsAdmin.config attr_reader :registry # Bootstrap CSS classes used for Navigation bar attr_accessor :navbar_css_classes # show Gravatar in Navigation bar attr_accessor :show_gravatar # accepts a hash of static links to be shown below the main navigation attr_accessor :navigation_static_links attr_accessor :navigation_static_label # Set where RailsAdmin fetches JS/CSS from, defaults to :sprockets attr_writer :asset_source # For customization of composite keys representation attr_accessor :composite_keys_serializer # Setup authentication to be run as a before filter # This is run inside the controller instance so you can setup any authentication you need to # # By default, the authentication will run via warden if available # and will run the default. # # If you use devise, this will authenticate the same as _authenticate_user!_ # # @example Devise admin # RailsAdmin.config do |config| # config.authenticate_with do # authenticate_admin! # end # end # # @example Custom Warden # RailsAdmin.config do |config| # config.authenticate_with do # warden.authenticate! scope: :paranoid # end # end # # @see RailsAdmin::Config::DEFAULT_AUTHENTICATION def authenticate_with(&blk) @authenticate = blk if blk @authenticate || DEFAULT_AUTHENTICATION end # Setup auditing/versioning provider that observe objects lifecycle def audit_with(*args, &block) extension = args.shift if extension klass = RailsAdmin::AUDITING_ADAPTERS[extension] klass.setup if klass.respond_to? :setup @audit = proc do @auditing_adapter = klass.new(*([self] + args).compact, &block) end elsif block @audit = block end @audit || DEFAULT_AUDIT end # Setup authorization to be run as a before filter # This is run inside the controller instance so you can setup any authorization you need to. # # By default, there is no authorization. # # @example Custom # RailsAdmin.config do |config| # config.authorize_with do # redirect_to root_path unless warden.user.is_admin? # end # end # # To use an authorization adapter, pass the name of the adapter. For example, # to use with CanCanCan[https://github.com/CanCanCommunity/cancancan/], pass it like this. # # @example CanCanCan # RailsAdmin.config do |config| # config.authorize_with :cancancan # end # # See the wiki[https://github.com/railsadminteam/rails_admin/wiki] for more on authorization. # # @see RailsAdmin::Config::DEFAULT_AUTHORIZE def authorize_with(*args, &block) extension = args.shift if extension klass = RailsAdmin::AUTHORIZATION_ADAPTERS[extension] klass.setup if klass.respond_to? :setup @authorize = proc do @authorization_adapter = klass.new(*([self] + args).compact, &block) end elsif block @authorize = block end @authorize || DEFAULT_AUTHORIZE end # Setup configuration using an extension-provided ConfigurationAdapter # # @example Custom configuration for role-based setup. # RailsAdmin.config do |config| # config.configure_with(:custom) do |config| # config.models = ['User', 'Comment'] # config.roles = { # 'Admin' => :all, # 'User' => ['User'] # } # end # end def configure_with(extension) configuration = RailsAdmin::CONFIGURATION_ADAPTERS[extension].new yield(configuration) if block_given? end # Setup a different method to determine the current user or admin logged in. # This is run inside the controller instance and made available as a helper. # # By default, _request.env["warden"].user_ or _current_user_ will be used. # # @example Custom # RailsAdmin.config do |config| # config.current_user_method do # current_admin # end # end # # @see RailsAdmin::Config::DEFAULT_CURRENT_USER def current_user_method(&block) @current_user = block if block @current_user || DEFAULT_CURRENT_USER end def default_search_operator=(operator) if %w[default like not_like starts_with ends_with is =].include? operator @default_search_operator = operator else raise ArgumentError.new("Search operator '#{operator}' not supported") end end # pool of all found model names from the whole application def models_pool (viable_models - excluded_models.collect(&:to_s)).uniq.sort end # Loads a model configuration instance from the registry or registers # a new one if one is yet to be added. # # First argument can be an instance of requested model, its class object, # its class name as a string or symbol or a RailsAdmin::AbstractModel # instance. # # If a block is given it is evaluated in the context of configuration instance. # # Returns given model's configuration # # @see RailsAdmin::Config.registry def model(entity, &block) key = case entity when RailsAdmin::AbstractModel entity.model.try(:name).try :to_sym when Class, ConstLoadSuppressor::ConstProxy entity.name.to_sym when String, Symbol entity.to_sym else entity.class.name.to_sym end @registry[key] ||= RailsAdmin::Config::LazyModel.new(key.to_s) @registry[key].add_deferred_block(&block) if block @registry[key] end def asset_source @asset_source ||= begin detected = defined?(Sprockets) ? :sprockets : :invalid unless ARGV.join(' ').include? 'rails_admin:install' warn <<~MSG [Warning] After upgrading RailsAdmin to 3.x you haven't set asset_source yet, using :#{detected} as the default. To suppress this message, run 'rails rails_admin:install' to setup the asset delivery method suitable to you. MSG end detected end end def default_hidden_fields=(fields) if fields.is_a?(Array) @default_hidden_fields = {} @default_hidden_fields[:edit] = fields @default_hidden_fields[:show] = fields else @default_hidden_fields = fields end end def parent_controller=(name) @parent_controller = name if defined?(RailsAdmin::ApplicationController) || defined?(RailsAdmin::MainController) RailsAdmin::Config::ConstLoadSuppressor.allowing do RailsAdmin.send(:remove_const, :ApplicationController) RailsAdmin.send(:remove_const, :MainController) load RailsAdmin::Engine.root.join('app/controllers/rails_admin/application_controller.rb') load RailsAdmin::Engine.root.join('app/controllers/rails_admin/main_controller.rb') end end end def total_columns_width=(_) ActiveSupport::Deprecation.warn('The total_columns_width configuration option is deprecated and has no effect.') end def sidescroll=(_) ActiveSupport::Deprecation.warn('The sidescroll configuration option was removed, it is always enabled now.') end # Setup actions to be used. def actions(&block) return unless block RailsAdmin::Config::Actions.reset RailsAdmin::Config::Actions.instance_eval(&block) end # Returns all model configurations # # @see RailsAdmin::Config.registry def models RailsAdmin::AbstractModel.all.collect { |m| model(m) } end # Reset all configurations to defaults. # # @see RailsAdmin::Config.registry def reset @compact_show_view = true @browser_validations = true @authenticate = nil @authorize = nil @audit = nil @current_user = nil @default_hidden_fields = {} @default_hidden_fields[:base] = [:_type] @default_hidden_fields[:edit] = %i[id _id created_at created_on deleted_at updated_at updated_on deleted_on] @default_hidden_fields[:show] = %i[id _id created_at created_on deleted_at updated_at updated_on deleted_on] @default_items_per_page = 20 @default_associated_collection_limit = 100 @default_search_operator = 'default' @excluded_models = [] @included_models = [] @label_methods = %i[name title] @main_app_name = proc { [Rails.application.engine_name.titleize.chomp(' Application'), 'Admin'] } @registry = {} @navbar_css_classes = %w[navbar-dark bg-primary border-bottom] @show_gravatar = true @navigation_static_links = {} @navigation_static_label = nil @asset_source = nil @composite_keys_serializer = RailsAdmin::Support::CompositeKeysSerializer @parent_controller = '::ActionController::Base' @forgery_protection_settings = {with: :exception} RailsAdmin::Config::Actions.reset RailsAdmin::AbstractModel.reset end # Reset a provided model's configuration. # # @see RailsAdmin::Config.registry def reset_model(model) key = model.is_a?(Class) ? model.name.to_sym : model.to_sym @registry.delete(key) end # Perform reset, then load RailsAdmin initializer again def reload! reset load RailsAdmin::Engine.config.initializer_path end # Get all models that are configured as visible sorted by their weight and label. # # @see RailsAdmin::Config::Hideable def visible_models(bindings) visible_models_with_bindings(bindings).sort do |a, b| if (weight_order = a.weight <=> b.weight) == 0 a.label.casecmp(b.label) else weight_order end end end private def viable_models included_models.collect(&:to_s).presence || begin @@system_models ||= # memoization for tests ([Rails.application] + Rails::Engine.subclasses.collect(&:instance)).flat_map do |app| (app.paths['app/models'].to_a + app.config.eager_load_paths).collect do |load_path| Dir.glob(app.root.join(load_path)).collect do |load_dir| path_prefix = "#{app.root.join(load_dir)}/" Dir.glob("#{load_dir}/**/*.rb").collect do |filename| # app/models/module/class.rb => module/class.rb => module/class => Module::Class filename.delete_prefix(path_prefix).chomp('.rb').camelize end end end end.flatten.reject { |m| m.starts_with?('Concerns::') } # rubocop:disable Style/MultilineBlockChain @@system_models + @registry.keys.collect(&:to_s) end end def visible_models_with_bindings(bindings) models.collect { |m| m.with(bindings) }.select do |m| m.visible? && RailsAdmin::Config::Actions.find(:index, bindings.merge(abstract_model: m.abstract_model)).try(:authorized?) && (!m.abstract_model.embedded? || m.abstract_model.cyclic?) end end end # Set default values for configuration options on load reset end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/engine.rb
lib/rails_admin/engine.rb
# frozen_string_literal: true require 'kaminari' require 'nested_form' require 'rails' require 'rails_admin' require 'rails_admin/extensions/url_for_extension' require 'rails_admin/version' require 'turbo-rails' module RailsAdmin class Engine < Rails::Engine isolate_namespace RailsAdmin attr_accessor :importmap config.action_dispatch.rescue_responses['RailsAdmin::ActionNotAllowed'] = :forbidden initializer 'RailsAdmin load UrlForExtension' do RailsAdmin::Engine.routes.singleton_class.prepend(RailsAdmin::Extensions::UrlForExtension) end initializer 'RailsAdmin reload config in development' do |app| config.initializer_path = app.root.join('config/initializers/rails_admin.rb') unless Rails.application.config.cache_classes ActiveSupport::Reloader.before_class_unload do RailsAdmin::Config.reload! end reloader = app.config.file_watcher.new([config.initializer_path], []) do # Do nothing, ActiveSupport::Reloader will trigger class_unload! anyway end app.reloaders << reloader app.reloader.to_run do reloader.execute_if_updated { require_unload_lock! } end reloader.execute end end initializer 'RailsAdmin precompile hook', group: :all do |app| case RailsAdmin.config.asset_source when :sprockets app.config.assets.precompile += %w[ rails_admin/application.js rails_admin/application.css ] app.config.assets.paths << RailsAdmin::Engine.root.join('src') require 'rails_admin/support/es_module_processor' Sprockets.register_bundle_processor 'application/javascript', RailsAdmin::Support::ESModuleProcessor when :importmap self.importmap = Importmap::Map.new.draw(app.root.join('config/importmap.rails_admin.rb')) end end # Check for required middlewares, users may forget to use them in Rails API mode config.after_initialize do |app| has_session_store = app.config.middleware.to_a.any? do |m| m.klass.try(:<=, ActionDispatch::Session::AbstractStore) || m.klass.try(:<=, ActionDispatch::Session::AbstractSecureStore) || m.klass.name =~ /^ActionDispatch::Session::/ end loaded = app.config.middleware.to_a.map(&:name) required = %w[ActionDispatch::Cookies ActionDispatch::Flash Rack::MethodOverride] missing = required - loaded unless missing.empty? && has_session_store configs = missing.map { |m| "config.middleware.use #{m}" } configs << "config.middleware.use #{app.config.session_store.try(:name) || 'ActionDispatch::Session::CookieStore'}, #{app.config.session_options}" unless has_session_store raise <<~ERROR Required middlewares for RailsAdmin are not added To fix this, add #{configs.join("\n ")} to config/application.rb. ERROR end RailsAdmin::Version.warn_with_js_version end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/abstract_model.rb
lib/rails_admin/abstract_model.rb
# frozen_string_literal: true require 'rails_admin/support/datetime' module RailsAdmin class AbstractModel cattr_accessor :all attr_reader :adapter, :model_name class << self def reset @@all = nil end def all(adapter = nil) @@all ||= Config.models_pool.collect { |m| new(m) }.compact adapter ? @@all.select { |m| m.adapter == adapter } : @@all end alias_method :old_new, :new def new(m) m = m.constantize unless m.is_a?(Class) (am = old_new(m)).model && am.adapter ? am : nil rescue *([LoadError, NameError] + (defined?(ActiveRecord) ? ['ActiveRecord::NoDatabaseError'.constantize, 'ActiveRecord::ConnectionNotEstablished'.constantize] : [])) puts "[RailsAdmin] Could not load model #{m}, assuming model is non existing. (#{$ERROR_INFO})" unless Rails.env.test? nil end @@polymorphic_parents = {} def polymorphic_parents(adapter, model_name, name) @@polymorphic_parents[adapter.to_sym] ||= {}.tap do |hash| all(adapter).each do |am| am.associations.select(&:as).each do |association| (hash[[association.klass.to_s.underscore, association.as].join('_').to_sym] ||= []) << am.model end end end @@polymorphic_parents[adapter.to_sym][[model_name.to_s.underscore, name].join('_').to_sym] end # For testing def reset_polymorphic_parents @@polymorphic_parents = {} end end def initialize(model_or_model_name) @model_name = model_or_model_name.to_s ancestors = model.ancestors.collect(&:to_s) if ancestors.include?('ActiveRecord::Base') && !model.abstract_class? && model.table_exists? initialize_active_record elsif ancestors.include?('Mongoid::Document') initialize_mongoid end end # do not store a reference to the model, does not play well with ActiveReload/Rails3.2 def model @model_name.constantize end def quoted_table_name table_name end def quote_column_name(name) name end def to_s model.to_s end def config Config.model self end def to_param @model_name.split('::').collect(&:underscore).join('~') end def param_key @model_name.split('::').collect(&:underscore).join('_') end def pretty_name model.model_name.human end def where(conditions) model.where(conditions) end def each_associated_children(object) associations.each do |association| case association.type when :has_one child = object.send(association.name) yield(association, [child]) if child when :has_many children = object.send(association.name) yield(association, Array.new(children)) end end end def format_id(id) id end def parse_id(id) id end private def initialize_active_record @adapter = :active_record require 'rails_admin/adapters/active_record' extend Adapters::ActiveRecord end def initialize_mongoid @adapter = :mongoid require 'rails_admin/adapters/mongoid' extend Adapters::Mongoid end def parse_field_value(field, value) value.is_a?(Array) ? value.map { |v| field.parse_value(v) } : field.parse_value(value) end class StatementBuilder def initialize(column, type, value, operator) @column = column @type = type @value = value @operator = operator end def to_statement return if [@operator, @value].any? { |v| v == '_discard' } unary_operators[@operator] || unary_operators[@value] || build_statement_for_type_generic end protected def get_filtering_duration FilteringDuration.new(@operator, @value).get_duration end def build_statement_for_type_generic build_statement_for_type || begin case @type when :date build_statement_for_date when :datetime, :timestamp, :time build_statement_for_datetime_or_timestamp end end end def build_statement_for_type raise 'You must override build_statement_for_type in your StatementBuilder' end def build_statement_for_integer_decimal_or_float case @value when Array val, range_begin, range_end = *@value.collect do |v| next unless v.to_i.to_s == v || v.to_f.to_s == v @type == :integer ? v.to_i : v.to_f end case @operator when 'between' range_filter(range_begin, range_end) else column_for_value(val) if val end else if @value.to_i.to_s == @value || @value.to_f.to_s == @value @type == :integer ? column_for_value(@value.to_i) : column_for_value(@value.to_f) end end end def build_statement_for_date start_date, end_date = get_filtering_duration if start_date start_date = begin start_date.to_date rescue StandardError nil end end if end_date end_date = begin end_date.to_date rescue StandardError nil end end range_filter(start_date, end_date) end def build_statement_for_datetime_or_timestamp start_date, end_date = get_filtering_duration start_date = start_date.beginning_of_day if start_date.is_a?(Date) end_date = end_date.end_of_day if end_date.is_a?(Date) range_filter(start_date, end_date) end def unary_operators raise 'You must override unary_operators in your StatementBuilder' end def range_filter(_min, _max) raise 'You must override range_filter in your StatementBuilder' end class FilteringDuration def initialize(operator, value) @value = value @operator = operator end def get_duration case @operator when 'between' then between when 'today' then today when 'yesterday' then yesterday when 'this_week' then this_week when 'last_week' then last_week else default end end def today [Date.today, Date.today] end def yesterday [Date.yesterday, Date.yesterday] end def this_week [Date.today.beginning_of_week, Date.today.end_of_week] end def last_week [1.week.ago.to_date.beginning_of_week, 1.week.ago.to_date.end_of_week] end def between [@value[1], @value[2]] end def default [default_date, default_date] end private def default_date Array.wrap(@value).first end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extension.rb
lib/rails_admin/extension.rb
# frozen_string_literal: true require 'rails_admin/extensions/controller_extension' module RailsAdmin EXTENSIONS = [] # rubocop:disable Style/MutableConstant AUTHORIZATION_ADAPTERS = {} # rubocop:disable Style/MutableConstant AUDITING_ADAPTERS = {} # rubocop:disable Style/MutableConstant CONFIGURATION_ADAPTERS = {} # rubocop:disable Style/MutableConstant # Extend RailsAdmin # # The extension may define various adapters (e.g., for authorization) and # register those via the options hash. def self.add_extension(extension_key, extension_definition, options = {}) options.assert_valid_keys(:authorization, :configuration, :auditing) EXTENSIONS << extension_key AUTHORIZATION_ADAPTERS[extension_key] = extension_definition::AuthorizationAdapter if options[:authorization] CONFIGURATION_ADAPTERS[extension_key] = extension_definition::ConfigurationAdapter if options[:configuration] AUDITING_ADAPTERS[extension_key] = extension_definition::AuditingAdapter if options[:auditing] end # Setup all extensions for testing def self.setup_all_extensions (AUTHORIZATION_ADAPTERS.values + AUDITING_ADAPTERS.values).each do |klass| klass.setup if klass.respond_to? :setup rescue # rubocop:disable Style/RescueStandardError # ignore errors end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/support/es_module_processor.rb
lib/rails_admin/support/es_module_processor.rb
# frozen_string_literal: true module RailsAdmin module Support class ESModuleProcessor def self.instance @instance ||= new end def self.call(input) instance.call(input) end def initialize; end def call(input) return unless input[:name] == 'rails_admin/application' input[:data].gsub(/^((?:import|export) .+)$/) { "// #{Regexp.last_match(1)}" } end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/support/csv_converter.rb
lib/rails_admin/support/csv_converter.rb
# frozen_string_literal: true require 'csv' module RailsAdmin class CSVConverter def initialize(objects = [], schema = nil) @fields = [] @associations = [] schema ||= {} return self if (@objects = objects).blank? @model = objects.dup.first.class @abstract_model = RailsAdmin::AbstractModel.new(@model) @model_config = @abstract_model.config @methods = [(schema[:only] || []) + (schema[:methods] || [])].flatten.compact @fields = @methods.collect { |m| export_field_for(m) }.compact @empty = ::I18n.t('admin.export.empty_value_for_associated_objects') schema_include = schema.delete(:include) || {} @associations = schema_include.each_with_object({}) do |(key, values), hash| association = export_field_for(key) next unless association&.association? model_config = association.associated_model_config abstract_model = model_config.abstract_model methods = [(values[:only] || []) + (values[:methods] || [])].flatten.compact hash[key] = { association: association, model: abstract_model.model, abstract_model: abstract_model, model_config: model_config, fields: methods.collect { |m| export_field_for(m, model_config) }.compact, } hash end end def to_csv(options = {}) if CSV::VERSION == '3.0.2' raise <<~MSG CSV library bundled with Ruby 2.6.0 has encoding issue, please upgrade Ruby to 2.6.1 or later. https://github.com/ruby/csv/issues/62 MSG end options = HashWithIndifferentAccess.new(options) encoding_to = Encoding.find(options[:encoding_to]) if options[:encoding_to].present? csv_string = generate_csv_string(options) csv_string = csv_string.encode(encoding_to, invalid: :replace, undef: :replace, replace: '?') if encoding_to # Add a BOM for utf8 encodings, helps with utf8 auto-detect for some versions of Excel. # Don't add if utf8 but user don't want to touch input encoding: # If user chooses utf8, they will open it in utf8 and BOM will disappear at reading. # But that way "English" users who don't bother and chooses to let utf8 by default won't get BOM added # and will not see it if Excel opens the file with a different encoding. csv_string = "\xEF\xBB\xBF#{csv_string}" if encoding_to == Encoding::UTF_8 [!options[:skip_header], (encoding_to || csv_string.encoding).to_s, csv_string] end private def export_field_for(method, model_config = @model_config) model_config.export.fields.detect { |f| f.name == method } end def generate_csv_string(options) generator_options = (options[:generator] || {}).symbolize_keys.delete_if { |_, value| value.blank? } method = @objects.respond_to?(:find_each) ? :find_each : :each CSV.generate(**generator_options) do |csv| csv << generate_csv_header unless options[:skip_header] @objects.send(method) do |object| csv << generate_csv_row(object) end end end def generate_csv_header @fields.collect do |field| ::I18n.t('admin.export.csv.header_for_root_methods', name: field.label, model: @abstract_model.pretty_name) end + @associations.flat_map do |_association_name, option_hash| option_hash[:fields].collect do |field| ::I18n.t('admin.export.csv.header_for_association_methods', name: field.label, association: option_hash[:association].label) end end end def generate_csv_row(object) @fields.collect do |field| field.with(object: object).export_value end + @associations.flat_map do |association_name, option_hash| associated_objects = [object.send(association_name)].flatten.compact option_hash[:fields].collect do |field| associated_objects.collect { |ao| field.with(object: ao).export_value.presence || @empty }.join(',') end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/support/hash_helper.rb
lib/rails_admin/support/hash_helper.rb
# frozen_string_literal: true module RailsAdmin class HashHelper def self.symbolize(obj) case obj when Array obj.each_with_object([]) do |val, res| res << case val when Hash, Array then symbolize(val) when String then val.to_sym else val end end when Hash obj.each_with_object({}) do |(key, val), res| nkey = key.is_a?(String) ? key.to_sym : key nval = case val when Hash, Array then symbolize(val) when String then val.to_sym else val end res[nkey] = nval end else obj end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/support/datetime.rb
lib/rails_admin/support/datetime.rb
# frozen_string_literal: true module RailsAdmin module Support class Datetime # Ruby format options as a key and flatpickr format options as a value FLATPICKR_TRANSLATIONS = { '%A' => 'l', # The full weekday name ("Sunday") '%a' => 'D', # The abbreviated weekday name ("Sun") '%B' => 'F', # The full month name ("January") '%b' => 'M', # The abbreviated month name ("Jan") '%D' => 'm/d/y', # American date format mm/dd/yy '%d' => 'd', # Day of the month (01..31) '%-d' => 'j', # Day of the month (1..31) '%e' => 'j', # Day of the month (1..31) '%F' => 'Y-m-d', # ISO 8601 date format '%H' => 'H', # Hour of the day, 24-hour clock (00..23) '%-H' => 'H', # Hour of the day, 24-hour clock (0..23) '%h' => 'M', # Same as %b '%I' => 'G', # Hour of the day, 12-hour clock (01..12) '%-I' => 'h', # Hour of the day, 12-hour clock (1..12) '%k' => 'H', # Hour of the day, 24-hour clock (0..23) '%l' => 'h', # Hour of the day, 12-hour clock (1..12) '%-l' => 'h', # Hour of the day, 12-hour clock (1..12) '%M' => 'i', # Minute of the hour (00..59) '%-M' => 'i', # Minute of the hour (00..59) '%m' => 'm', # Month of the year (01..12) '%-m' => 'n', # Month of the year (1..12) '%P' => 'K', # Meridian indicator ('am' or 'pm') '%p' => 'K', # Meridian indicator ('AM' or 'PM') '%R' => 'H:i', # 24-hour time (%H:%M) '%r' => 'G:i:S K', # 12-hour time (%I:%M:%S %p) '%S' => 'S', # Second of the minute (00..60) '%-S' => 's', # Second of the minute (0..60) '%s' => 'U', # Number of seconds since 1970-01-01 00:00:00 UTC. '%T' => 'H:i:S', # 24-hour time (%H:%M:%S) '%U' => 'W', # Week number of the year. The week starts with Sunday. (00..53) '%w' => 'w', # Day of the week (Sunday is 0, 0..6) '%X' => 'H:i:S', # Same as %T '%x' => 'm/d/y', # Same as %D '%Y' => 'Y', # Year with century '%y' => 'y', # Year without a century (00..99) '%%' => '%', }.freeze class << self def to_flatpickr_format(strftime_format) strftime_format.gsub(/(?<!%)(?<![-0-9:])\w/, '\\\\\0').gsub(/%([-0-9:]?\w)/) do |match| # Timezone can't be handled by frontend, the server's one is always used case match when '%Z', '%:z' # Time zone as hour and minute offset from UTC with a colon (e.g. +09:00) Time.zone.formatted_offset when '%z' # Time zone as hour and minute offset from UTC (e.g. +0900) Time.zone.formatted_offset(false) else FLATPICKR_TRANSLATIONS[match] or raise <<~MSG Unsupported strftime directive '#{match}' was found. Please consider explicitly setting flatpickr_format instance option for the field. field(:name_of_field) { flatpickr_format '...' } MSG end end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/support/composite_keys_serializer.rb
lib/rails_admin/support/composite_keys_serializer.rb
# frozen_string_literal: true module RailsAdmin module Support module CompositeKeysSerializer def self.serialize(keys) keys.map { |key| key&.to_s&.gsub('_', '__') }.join('_') end def self.deserialize(string) string.split('_').map { |key| key&.gsub('__', '_') } end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extensions/url_for_extension.rb
lib/rails_admin/extensions/url_for_extension.rb
# frozen_string_literal: true module RailsAdmin module Extensions module UrlForExtension def url_for(options, *args) case options[:id] when Array options[:id] = RailsAdmin.config.composite_keys_serializer.serialize(options[:id]) end super options, *args end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extensions/pundit.rb
lib/rails_admin/extensions/pundit.rb
# frozen_string_literal: true require 'rails_admin/extensions/pundit/authorization_adapter' RailsAdmin.add_extension(:pundit, RailsAdmin::Extensions::Pundit, authorization: true)
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extensions/paper_trail.rb
lib/rails_admin/extensions/paper_trail.rb
# frozen_string_literal: true require 'rails_admin/extensions/paper_trail/auditing_adapter' RailsAdmin.add_extension(:paper_trail, RailsAdmin::Extensions::PaperTrail, auditing: true)
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extensions/cancancan.rb
lib/rails_admin/extensions/cancancan.rb
# frozen_string_literal: true require 'rails_admin/extensions/cancancan/authorization_adapter' RailsAdmin.add_extension(:cancancan, RailsAdmin::Extensions::CanCanCan, authorization: true)
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extensions/controller_extension.rb
lib/rails_admin/extensions/controller_extension.rb
# frozen_string_literal: true module RailsAdmin module Extensions module ControllerExtension end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extensions/paper_trail/auditing_adapter.rb
lib/rails_admin/extensions/paper_trail/auditing_adapter.rb
# frozen_string_literal: true require 'active_support/core_ext/string/strip' module RailsAdmin module Extensions module PaperTrail class VersionProxy def initialize(version, user_class = User) @version = version @user_class = user_class end def message @message = @version.event @version.respond_to?(:changeset) && @version.changeset.present? ? @message + ' [' + @version.changeset.to_a.collect { |c| "#{c[0]} = #{c[1][1]}" }.join(', ') + ']' : @message end def created_at @version.created_at end def table @version.item_type end def username begin @user_class.find(@version.whodunnit).try(:email) rescue StandardError nil end || @version.whodunnit end def item @version.item_id end end module ControllerExtension def user_for_paper_trail _current_user.try(:id) || _current_user end end class AuditingAdapter COLUMN_MAPPING = { table: :item_type, username: :whodunnit, item: :item_id, created_at: :created_at, message: :event, }.freeze E_USER_CLASS_NOT_SET = <<~ERROR Please set up PaperTrail's user class explicitly. config.audit_with :paper_trail do user_class { User } end ERROR E_VERSION_MODEL_NOT_SET = <<~ERROR Please set up PaperTrail's version model explicitly. config.audit_with :paper_trail do version_class { PaperTrail::Version } end If you have configured a model to use a custom version class (https://github.com/paper-trail-gem/paper_trail#6a-custom-version-classes) that configuration will take precedence over what you specify in `audit_with`. ERROR include RailsAdmin::Config::Configurable def self.setup raise 'PaperTrail not found' unless defined?(::PaperTrail) RailsAdmin::Extensions::ControllerExtension.include ControllerExtension end def initialize(controller, user_class_name = nil, version_class_name = nil, &block) @controller = controller @controller&.send(:set_paper_trail_whodunnit) user_class { user_class_name.to_s.constantize } if user_class_name version_class { version_class_name.to_s.constantize } if version_class_name instance_eval(&block) if block end register_instance_option :user_class do User rescue NameError raise E_USER_CLASS_NOT_SET end register_instance_option :version_class do PaperTrail::Version rescue NameError raise E_VERSION_MODEL_NOT_SET end register_instance_option :sort_by do {id: :desc} end def latest(count = 100) version_class. order(sort_by).includes(:item).limit(count). collect { |version| VersionProxy.new(version, user_class) } end def delete_object(_object, _model, _user) # do nothing end def update_object(_object, _model, _user, _changes) # do nothing end def create_object(_object, _abstract_model, _user) # do nothing end def listing_for_model(model, query, sort, sort_reverse, all, page, per_page = (RailsAdmin::Config.default_items_per_page || 20)) listing_for_model_or_object(model, nil, query, sort, sort_reverse, all, page, per_page) end def listing_for_object(model, object, query, sort, sort_reverse, all, page, per_page = (RailsAdmin::Config.default_items_per_page || 20)) listing_for_model_or_object(model, object, query, sort, sort_reverse, all, page, per_page) end protected # - model - a RailsAdmin::AbstractModel def listing_for_model_or_object(model, object, query, sort, sort_reverse, all, page, per_page) sort = if sort.present? {COLUMN_MAPPING[sort.to_sym] => sort_reverse ? :desc : :asc} else sort_by end current_page = page.presence || '1' versions = object.nil? ? versions_for_model(model) : object.public_send(model.model.versions_association_name) versions = versions.where('event LIKE ?', "%#{query}%") if query.present? versions = versions.order(sort) versions = versions.send(Kaminari.config.page_method_name, current_page).per(per_page) unless all paginated_proxies = Kaminari.paginate_array([], total_count: versions.try(:total_count) || versions.count) paginated_proxies = paginated_proxies.send( paginated_proxies.respond_to?(Kaminari.config.page_method_name) ? Kaminari.config.page_method_name : :page, current_page, ).per(per_page) versions.each do |version| paginated_proxies << VersionProxy.new(version, user_class) end paginated_proxies end def versions_for_model(model) model_name = model.model.name base_class_name = model.model.base_class.name options = if base_class_name == model_name {item_type: model_name} else {item_type: base_class_name, item_id: model.model.all} end version_class_for(model.model).where(options) end # PT can be configured to use [custom version # classes](https://github.com/paper-trail-gem/paper_trail#6a-custom-version-classes) # # ```ruby # has_paper_trail versions: { class_name: 'MyVersion' } # ``` def version_class_for(model) model.paper_trail.version_class end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extensions/cancancan/authorization_adapter.rb
lib/rails_admin/extensions/cancancan/authorization_adapter.rb
# frozen_string_literal: true module RailsAdmin module Extensions module CanCanCan # This adapter is for the CanCanCan[https://github.com/CanCanCommunity/cancancan] authorization library. class AuthorizationAdapter module ControllerExtension def current_ability # use _current_user instead of default current_user so it works with # whatever current user method is defined with RailsAdmin @current_ability ||= ability_class.new(_current_user) end end include RailsAdmin::Config::Configurable def self.setup RailsAdmin::Extensions::ControllerExtension.include ControllerExtension end # See the +authorize_with+ config method for where the initialization happens. def initialize(controller, ability = nil, &block) @controller = controller ability_class { ability } if ability instance_eval(&block) if block adapter = self ControllerExtension.define_method(:ability_class) do adapter.ability_class end @controller.current_ability.authorize! :access, :rails_admin end register_instance_option :ability_class do Ability end # This method is called in every controller action and should raise an exception # when the authorization fails. The first argument is the name of the controller # action as a symbol (:create, :bulk_delete, etc.). The second argument is the # AbstractModel instance that applies. The third argument is the actual model # instance if it is available. def authorize(action, abstract_model = nil, model_object = nil) return unless action action, subject = resolve_action_and_subject(action, abstract_model, model_object) @controller.current_ability.authorize!(action, subject) end # This method is called primarily from the view to determine whether the given user # has access to perform the action on a given model. It should return true when authorized. # This takes the same arguments as +authorize+. The difference is that this will # return a boolean whereas +authorize+ will raise an exception when not authorized. def authorized?(action, abstract_model = nil, model_object = nil) return unless action action, subject = resolve_action_and_subject(action, abstract_model, model_object) @controller.current_ability.can?(action, subject) end # This is called when needing to scope a database query. It is called within the list # and bulk_delete/destroy actions and should return a scope which limits the records # to those which the user can perform the given action on. def query(action, abstract_model) abstract_model.model.accessible_by(@controller.current_ability, action) end # This is called in the new/create actions to determine the initial attributes for new # records. It should return a hash of attributes which match what the user # is authorized to create. def attributes_for(action, abstract_model) @controller.current_ability.attributes_for(action, abstract_model&.model) end private def resolve_action_and_subject(action, abstract_model, model_object) subject = model_object || abstract_model&.model if subject [action, subject] else # For :dashboard compatibility [:read, action] end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/extensions/pundit/authorization_adapter.rb
lib/rails_admin/extensions/pundit/authorization_adapter.rb
# frozen_string_literal: true module RailsAdmin module Extensions module Pundit # This adapter is for the Pundit[https://github.com/elabs/pundit] authorization library. # You can create another adapter for different authorization behavior, just be certain it # responds to each of the public methods here. class AuthorizationAdapter # This method is called first time only and used for setup def self.setup RailsAdmin::Extensions::ControllerExtension.include defined?(::Pundit::Authorization) ? ::Pundit::Authorization : ::Pundit end # See the +authorize_with+ config method for where the initialization happens. def initialize(controller) @controller = controller end # This method is called in every controller action and should raise an exception # when the authorization fails. The first argument is the name of the controller # action as a symbol (:create, :bulk_delete, etc.). The second argument is the # AbstractModel instance that applies. The third argument is the actual model # instance if it is available. def authorize(action, abstract_model = nil, model_object = nil) record = model_object || abstract_model&.model raise ::Pundit::NotAuthorizedError.new("not allowed to #{action} this #{record}") if action && !policy(record).send(action_for_pundit(action)) @controller.instance_variable_set(:@_pundit_policy_authorized, true) end # This method is called primarily from the view to determine whether the given user # has access to perform the action on a given model. It should return true when authorized. # This takes the same arguments as +authorize+. The difference is that this will # return a boolean whereas +authorize+ will raise an exception when not authorized. def authorized?(action, abstract_model = nil, model_object = nil) record = model_object || abstract_model&.model policy(record).send(action_for_pundit(action)) if action end # This is called when needing to scope a database query. It is called within the list # and bulk_delete/destroy actions and should return a scope which limits the records # to those which the user can perform the given action on. def query(_action, abstract_model) @controller.send(:policy_scope, abstract_model.model.all) rescue ::Pundit::NotDefinedError abstract_model.model.all end # This is called in the new/create actions to determine the initial attributes for new # records. It should return a hash of attributes which match what the user # is authorized to create. def attributes_for(action, abstract_model) record = abstract_model&.model policy(record).try(:attributes_for, action) || {} end private def policy(record) @controller.send(:policy, record) rescue ::Pundit::NotDefinedError ::ApplicationPolicy.new(@controller.send(:pundit_user), record) end def action_for_pundit(action) action[-1, 1] == '?' ? action : "#{action}?" end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/active_record.rb
lib/rails_admin/adapters/active_record.rb
# frozen_string_literal: true require 'active_record' require 'rails_admin/adapters/active_record/association' require 'rails_admin/adapters/active_record/object_extension' require 'rails_admin/adapters/active_record/property' module RailsAdmin module Adapters module ActiveRecord DISABLED_COLUMN_TYPES = %i[tsvector blob binary spatial hstore geometry].freeze def new(params = {}) model.new(params).extend(ObjectExtension) end def get(id, scope = scoped) object = primary_key_scope(scope, id).first return unless object object.extend(ObjectExtension) end def scoped model.all end def first(options = {}, scope = nil) all(options, scope).first end def all(options = {}, scope = nil) scope ||= scoped scope = scope.includes(options[:include]) if options[:include] scope = scope.limit(options[:limit]) if options[:limit] scope = bulk_scope(scope, options) if options[:bulk_ids] scope = query_scope(scope, options[:query]) if options[:query] scope = filter_scope(scope, options[:filters]) if options[:filters] scope = scope.send(Kaminari.config.page_method_name, options[:page]).per(options[:per]) if options[:page] && options[:per] scope = sort_scope(scope, options) if options[:sort] scope end def count(options = {}, scope = nil) all(options.merge(limit: false, page: false), scope).count(:all) end def destroy(objects) Array.wrap(objects).each(&:destroy) end def associations model.reflect_on_all_associations.collect do |association| Association.new(association, model) end end def properties columns = model.columns.reject do |c| c.type.blank? || DISABLED_COLUMN_TYPES.include?(c.type.to_sym) || c.try(:array) end columns.collect do |property| Property.new(property, model) end end def base_class model.base_class end delegate :primary_key, :table_name, to: :model, prefix: false def quoted_table_name model.quoted_table_name end def quote_column_name(name) model.connection.quote_column_name(name) end def encoding adapter = if ::ActiveRecord::Base.respond_to?(:connection_db_config) ::ActiveRecord::Base.connection_db_config.configuration_hash[:adapter] else ::ActiveRecord::Base.connection_config[:adapter] end case adapter when 'postgresql' ::ActiveRecord::Base.connection.select_one("SELECT ''::text AS str;").values.first.encoding when 'mysql2' if RUBY_ENGINE == 'jruby' ::ActiveRecord::Base.connection.select_one("SELECT '' AS str;").values.first.encoding else ::ActiveRecord::Base.connection.raw_connection.encoding end when 'oracle_enhanced' ::ActiveRecord::Base.connection.select_one('SELECT dummy FROM DUAL').values.first.encoding else ::ActiveRecord::Base.connection.select_one("SELECT '' AS str;").values.first.encoding end end def embedded? false end def cyclic? false end def adapter_supports_joins? true end def format_id(id) if primary_key.is_a? Array RailsAdmin.config.composite_keys_serializer.serialize(id) else id end end def parse_id(id) if primary_key.is_a?(Array) ids = RailsAdmin.config.composite_keys_serializer.deserialize(id) primary_key.each_with_index do |key, i| ids[i] = model.type_for_attribute(key).cast(ids[i]) end ids else id end end private def primary_key_scope(scope, id) if primary_key.is_a? Array scope.where(primary_key.zip(parse_id(id)).to_h) else scope.where(primary_key => id) end end def bulk_scope(scope, options) if primary_key.is_a? Array options[:bulk_ids].map { |id| primary_key_scope(scope, id) }.reduce(&:or) else scope.where(primary_key => options[:bulk_ids]) end end def sort_scope(scope, options) direction = options[:sort_reverse] ? :asc : :desc case options[:sort] when String, Symbol scope.reorder("#{options[:sort]} #{direction}") when Array scope.reorder(options[:sort].zip(Array.new(options[:sort].size) { direction }).to_h) when Hash scope.reorder(options[:sort].map { |table_name, column| "#{table_name}.#{column}" }. zip(Array.new(options[:sort].size) { direction }).to_h) else raise ArgumentError.new("Unsupported sort value: #{options[:sort]}") end end class WhereBuilder def initialize(scope) @statements = [] @values = [] @tables = [] @scope = scope end def add(field, value, operator) field.searchable_columns.flatten.each do |column_infos| statement, value1, value2 = StatementBuilder.new(column_infos[:column], column_infos[:type], value, operator, @scope.connection.adapter_name).to_statement @statements << statement if statement.present? @values << value1 unless value1.nil? @values << value2 unless value2.nil? table, column = column_infos[:column].split('.') @tables.push(table) if column end end def build scope = @scope.where(@statements.join(' OR '), *@values) scope = scope.references(*@tables.uniq) if @tables.any? scope end end def query_scope(scope, query, fields = config.list.fields.select(&:queryable?)) if config.list.search_by scope.send(config.list.search_by, query) else wb = WhereBuilder.new(scope) fields.each do |field| value = parse_field_value(field, query) wb.add(field, value, field.search_operator) end # OR all query statements wb.build end end # filters example => {"string_field"=>{"0055"=>{"o"=>"like", "v"=>"test_value"}}, ...} # "0055" is the filter index, no use here. o is the operator, v the value def filter_scope(scope, filters, fields = config.list.fields.select(&:filterable?)) filters.each_pair do |field_name, filters_dump| filters_dump.each_value do |filter_dump| wb = WhereBuilder.new(scope) field = fields.detect { |f| f.name.to_s == field_name } value = parse_field_value(field, filter_dump[:v]) wb.add(field, value, (filter_dump[:o] || RailsAdmin::Config.default_search_operator)) # AND current filter statements to other filter statements scope = wb.build end end scope end def build_statement(column, type, value, operator) StatementBuilder.new(column, type, value, operator, model.connection.adapter_name).to_statement end class StatementBuilder < RailsAdmin::AbstractModel::StatementBuilder def initialize(column, type, value, operator, adapter_name) super column, type, value, operator @adapter_name = adapter_name end protected def unary_operators case @type when :boolean boolean_unary_operators when :uuid uuid_unary_operators when :integer, :decimal, :float numeric_unary_operators else generic_unary_operators end end private def generic_unary_operators { '_blank' => ["(#{@column} IS NULL OR #{@column} = '')"], '_present' => ["(#{@column} IS NOT NULL AND #{@column} != '')"], '_null' => ["(#{@column} IS NULL)"], '_not_null' => ["(#{@column} IS NOT NULL)"], '_empty' => ["(#{@column} = '')"], '_not_empty' => ["(#{@column} != '')"], } end def boolean_unary_operators generic_unary_operators.merge( '_blank' => ["(#{@column} IS NULL)"], '_empty' => ["(#{@column} IS NULL)"], '_present' => ["(#{@column} IS NOT NULL)"], '_not_empty' => ["(#{@column} IS NOT NULL)"], ) end alias_method :numeric_unary_operators, :boolean_unary_operators alias_method :uuid_unary_operators, :boolean_unary_operators def range_filter(min, max) if min && max && min == max ["(#{@column} = ?)", min] elsif min && max ["(#{@column} BETWEEN ? AND ?)", min, max] elsif min ["(#{@column} >= ?)", min] elsif max ["(#{@column} <= ?)", max] end end def build_statement_for_type case @type when :boolean then build_statement_for_boolean when :integer, :decimal, :float then build_statement_for_integer_decimal_or_float when :string, :text, :citext then build_statement_for_string_or_text when :enum then build_statement_for_enum when :belongs_to_association then build_statement_for_belongs_to_association when :uuid then build_statement_for_uuid end end def build_statement_for_boolean case @value when 'false', 'f', '0' ["(#{@column} IS NULL OR #{@column} = ?)", false] when 'true', 't', '1' ["(#{@column} = ?)", true] end end def column_for_value(value) ["(#{@column} = ?)", value] end def build_statement_for_belongs_to_association return if @value.blank? ["(#{@column} = ?)", @value.to_i] if @value.to_i.to_s == @value end def build_statement_for_string_or_text return if @value.blank? return ["(#{@column} = ?)", @value] if ['is', '='].include?(@operator) @value = @value.mb_chars.downcase unless %w[postgresql postgis].include? ar_adapter @value = case @operator when 'default', 'like', 'not_like' "%#{@value}%" when 'starts_with' "#{@value}%" when 'ends_with' "%#{@value}" else return end if %w[postgresql postgis].include? ar_adapter if @operator == 'not_like' ["(#{@column} NOT ILIKE ?)", @value] else ["(#{@column} ILIKE ?)", @value] end elsif @operator == 'not_like' ["(LOWER(#{@column}) NOT LIKE ?)", @value] else ["(LOWER(#{@column}) LIKE ?)", @value] end end def build_statement_for_enum return if @value.blank? ["(#{@column} IN (?))", Array.wrap(@value)] end def build_statement_for_uuid column_for_value(@value) if /\A[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\z/.match?(@value.to_s) end def ar_adapter @adapter_name.downcase end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/mongoid.rb
lib/rails_admin/adapters/mongoid.rb
# frozen_string_literal: true require 'mongoid' require 'rails_admin/config/sections/list' require 'rails_admin/adapters/mongoid/association' require 'rails_admin/adapters/mongoid/object_extension' require 'rails_admin/adapters/mongoid/property' require 'rails_admin/adapters/mongoid/bson' module RailsAdmin module Adapters module Mongoid DISABLED_COLUMN_TYPES = %w[Range Moped::BSON::Binary BSON::Binary Mongoid::Geospatial::Point].freeze def parse_object_id(value) Bson.parse_object_id(value) end def new(params = {}) model.new(params).extend(ObjectExtension) end def get(id, scope = scoped) object = scope.find(id) return nil unless object object.extend(ObjectExtension) rescue StandardError => e raise e if %w[ Mongoid::Errors::DocumentNotFound Mongoid::Errors::InvalidFind Moped::Errors::InvalidObjectId BSON::InvalidObjectId BSON::Error::InvalidObjectId ].exclude?(e.class.to_s) end def scoped model.scoped end def first(options = {}, scope = nil) all(options, scope).first end def all(options = {}, scope = nil) scope ||= scoped scope = scope.includes(*options[:include]) if options[:include] scope = scope.limit(options[:limit]) if options[:limit] scope = scope.any_in(_id: options[:bulk_ids]) if options[:bulk_ids] scope = query_scope(scope, options[:query]) if options[:query] scope = filter_scope(scope, options[:filters]) if options[:filters] scope = scope.send(Kaminari.config.page_method_name, options[:page]).per(options[:per]) if options[:page] && options[:per] scope = sort_by(options, scope) if options[:sort] scope rescue NoMethodError => e if /page/.match?(e.message) e = e.exception <<~ERROR #{e.message} If you don't have kaminari-mongoid installed, add `gem 'kaminari-mongoid'` to your Gemfile. ERROR end raise e end def count(options = {}, scope = nil) all(options.merge(limit: false, page: false), scope).count end def destroy(objects) Array.wrap(objects).each(&:destroy) end def primary_key '_id' end def associations model.relations.values.collect do |association| Association.new(association, model) end end def properties fields = model.fields.reject { |_name, field| DISABLED_COLUMN_TYPES.include?(field.type.to_s) } fields.collect { |_name, field| Property.new(field, model) } end def base_class klass = model klass = klass.superclass while klass.hereditary? klass end def table_name model.collection_name.to_s end def encoding Encoding::UTF_8 end def embedded? associations.detect { |a| a.macro == :embedded_in } end def cyclic? model.cyclic? end def adapter_supports_joins? false end private def build_statement(column, type, value, operator) StatementBuilder.new(column, type, value, operator).to_statement end def make_field_conditions(field, value, operator) conditions_per_collection = {} field.searchable_columns.each do |column_infos| collection_name, column_name = parse_collection_name(column_infos[:column]) statement = build_statement(column_name, column_infos[:type], value, operator) next unless statement conditions_per_collection[collection_name] ||= [] conditions_per_collection[collection_name] << statement end conditions_per_collection end def query_scope(scope, query, fields = config.list.fields.select(&:queryable?)) if config.list.search_by scope.send(config.list.search_by, query) else statements = [] fields.each do |field| value = parse_field_value(field, query) conditions_per_collection = make_field_conditions(field, value, field.search_operator) statements.concat make_condition_for_current_collection(field, conditions_per_collection) end scope.where(statements.any? ? {'$or' => statements} : {}) end end # filters example => {"string_field"=>{"0055"=>{"o"=>"like", "v"=>"test_value"}}, ...} # "0055" is the filter index, no use here. o is the operator, v the value def filter_scope(scope, filters, fields = config.list.fields.select(&:filterable?)) statements = [] filters.each_pair do |field_name, filters_dump| filters_dump.each_value do |filter_dump| field = fields.detect { |f| f.name.to_s == field_name } next unless field value = parse_field_value(field, filter_dump[:v]) conditions_per_collection = make_field_conditions(field, value, (filter_dump[:o] || 'default')) field_statements = make_condition_for_current_collection(field, conditions_per_collection) if field_statements.many? statements << {'$or' => field_statements} elsif field_statements.any? statements << field_statements.first end end end scope.where(statements.any? ? {'$and' => statements} : {}) end def parse_collection_name(column) collection_name, column_name = column.split('.') if associations.detect { |a| a.name == collection_name.to_sym }.try(:embeds?) [table_name, column] else [collection_name, column_name] end end def make_condition_for_current_collection(target_field, conditions_per_collection) result = [] conditions_per_collection.each do |collection_name, conditions| if collection_name == table_name # conditions referring current model column are passed directly result.concat conditions else # otherwise, collect ids of documents that satisfy search condition result.concat perform_search_on_associated_collection(target_field.name, conditions) end end result end def perform_search_on_associated_collection(field_name, conditions) target_association = associations.detect { |a| a.name == field_name } return [] unless target_association model = target_association.klass case target_association.type when :belongs_to, :has_and_belongs_to_many [{target_association.foreign_key.to_s => {'$in' => model.where('$or' => conditions).all.collect { |r| r.send(target_association.primary_key) }}}] when :has_many, :has_one [{target_association.primary_key.to_s => {'$in' => model.where('$or' => conditions).all.collect { |r| r.send(target_association.foreign_key) }}}] end end def sort_by(options, scope) return scope unless options[:sort] case options[:sort] when String field_name, collection_name = options[:sort].split('.').reverse raise 'sorting by associated model column is not supported in Non-Relational databases' if collection_name && collection_name != table_name when Symbol field_name = options[:sort].to_s end if options[:sort_reverse] scope.asc field_name else scope.desc field_name end end class StatementBuilder < RailsAdmin::AbstractModel::StatementBuilder protected def unary_operators { '_blank' => {@column => {'$in' => [nil, '']}}, '_present' => {@column => {'$nin' => [nil, '']}}, '_null' => {@column => nil}, '_not_null' => {@column => {'$ne' => nil}}, '_empty' => {@column => ''}, '_not_empty' => {@column => {'$ne' => ''}}, } end private def build_statement_for_type case @type when :boolean then build_statement_for_boolean when :integer, :decimal, :float then build_statement_for_integer_decimal_or_float when :string, :text then build_statement_for_string_or_text when :enum then build_statement_for_enum when :belongs_to_association, :bson_object_id then build_statement_for_belongs_to_association_or_bson_object_id end end def build_statement_for_boolean case @value when 'false', 'f', '0' {@column => false} when 'true', 't', '1' {@column => true} end end def column_for_value(value) {@column => value} end def build_statement_for_string_or_text return if @value.blank? @value = case @operator when 'not_like' Regexp.compile("^((?!#{Regexp.escape(@value)}).)*$", Regexp::IGNORECASE) when 'default', 'like' Regexp.compile(Regexp.escape(@value), Regexp::IGNORECASE) when 'starts_with' Regexp.compile("^#{Regexp.escape(@value)}", Regexp::IGNORECASE) when 'ends_with' Regexp.compile("#{Regexp.escape(@value)}$", Regexp::IGNORECASE) when 'is', '=' @value.to_s else return end {@column => @value} end def build_statement_for_enum return if @value.blank? {@column => {'$in' => Array.wrap(@value)}} end def build_statement_for_belongs_to_association_or_bson_object_id {@column => @value} if @value end def range_filter(min, max) if min && max && min == max {@column => min} elsif min && max {@column => {'$gte' => min, '$lte' => max}} elsif min {@column => {'$gte' => min}} elsif max {@column => {'$lte' => max}} end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/mongoid/bson.rb
lib/rails_admin/adapters/mongoid/bson.rb
# frozen_string_literal: true require 'mongoid' module RailsAdmin module Adapters module Mongoid class Bson OBJECT_ID = if defined?(Moped::BSON) Moped::BSON::ObjectId elsif defined?(BSON::ObjectId) BSON::ObjectId end class << self def parse_object_id(value) OBJECT_ID.from_string(value) rescue StandardError => e raise e if %w[ Moped::Errors::InvalidObjectId BSON::ObjectId::Invalid BSON::InvalidObjectId BSON::Error::InvalidObjectId ].exclude?(e.class.to_s) end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/mongoid/object_extension.rb
lib/rails_admin/adapters/mongoid/object_extension.rb
# frozen_string_literal: true module RailsAdmin module Adapters module Mongoid module ObjectExtension def self.extended(object) object.associations.each do |name, association| association = Association.new(association, object.class) case association.macro when :has_many unless association.autosave? object.singleton_class.after_create do send(name).each(&:save) end end when :has_one unless association.autosave? object.singleton_class.after_create do send(name)&.save end end end end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/mongoid/property.rb
lib/rails_admin/adapters/mongoid/property.rb
# frozen_string_literal: true module RailsAdmin module Adapters module Mongoid class Property STRING_TYPE_COLUMN_NAMES = %i[name title subject].freeze attr_reader :property, :model def initialize(property, model) @property = property @model = model end def name (property.options[:as] || property.name).to_sym end def pretty_name (property.options[:as] || property.name).to_s.tr('_', ' ').capitalize end def type case property.type.to_s when 'Array', 'Hash', 'Money' :serialized when 'BigDecimal' :decimal when 'Boolean', 'Mongoid::Boolean' :boolean when 'BSON::ObjectId', 'Moped::BSON::ObjectId' :bson_object_id when 'Date' :date when 'ActiveSupport::TimeWithZone', 'DateTime', 'Time' :datetime when 'Float' :float when 'Integer' :integer when 'Object' object_field_type when 'String' string_field_type when 'Symbol' :string else :string end end def length (length_validation_lookup || 255) if type == :string end def nullable? true end def serial? name == :_id end def association? false end def read_only? model.readonly_attributes.include? property.name.to_s end private def object_field_type association = Association.new model.relations.values.detect { |r| r.try(:foreign_key).try(:to_sym) == name }, model if %i[belongs_to referenced_in embedded_in].include?(association.macro) :bson_object_id else :string end end def string_field_type if ((length = length_validation_lookup) && length < 256) || STRING_TYPE_COLUMN_NAMES.include?(name) :string else :text end end def length_validation_lookup shortest = model.validators.select { |validator| validator.respond_to?(:attributes) && validator.attributes.include?(name.to_sym) && validator.kind == :length && validator.options[:maximum] }.min do |a, b| a.options[:maximum] <=> b.options[:maximum] end shortest && shortest.options[:maximum] end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/mongoid/extension.rb
lib/rails_admin/adapters/mongoid/extension.rb
# frozen_string_literal: true module RailsAdmin module Adapters module Mongoid module Extension extend ActiveSupport::Concern included do class_attribute :nested_attributes_options self.nested_attributes_options = {} class << self def rails_admin(&block) RailsAdmin.config(self, &block) end alias_method :accepts_nested_attributes_for_without_rails_admin, :accepts_nested_attributes_for alias_method :accepts_nested_attributes_for, :accepts_nested_attributes_for_with_rails_admin end end def rails_admin_default_object_label_method new_record? ? "new #{self.class}" : "#{self.class} ##{id}" end def safe_send(value) if attributes.detect { |k, _v| k.to_s == value.to_s } read_attribute(value) else send(value) end end module ClassMethods # Mongoid accepts_nested_attributes_for does not store options in accessible scope, # so we intercept the call and store it in instance variable which can be accessed from outside def accepts_nested_attributes_for_with_rails_admin(*args) options = args.extract_options! args.each do |arg| nested_attributes_options[arg.to_sym] = options.reverse_merge(allow_destroy: false, update_only: false) end args << options accepts_nested_attributes_for_without_rails_admin(*args) end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/mongoid/association.rb
lib/rails_admin/adapters/mongoid/association.rb
# frozen_string_literal: true module RailsAdmin module Adapters module Mongoid class Association attr_reader :association, :model delegate :autosave?, to: :association def initialize(association, model) @association = association @model = model end def name association.name.to_sym end def pretty_name name.to_s.tr('_', ' ').capitalize end def type case macro.to_sym when :belongs_to, :referenced_in, :embedded_in :belongs_to when :has_one, :references_one, :embeds_one :has_one when :has_many, :references_many, :embeds_many :has_many when :has_and_belongs_to_many, :references_and_referenced_in_many :has_and_belongs_to_many else raise "Unknown association type: #{macro.inspect}" end end def field_type if polymorphic? :polymorphic_association else :"#{type}_association" end end def klass if polymorphic? && %i[referenced_in belongs_to].include?(macro) polymorphic_parents(:mongoid, association.inverse_class_name, name) || [] else association.klass end end def primary_key case type when :belongs_to, :has_and_belongs_to_many association.primary_key.to_sym else :_id end end def foreign_key return if embeds? begin association.foreign_key.to_sym rescue StandardError nil end end def foreign_key_nullable? return if foreign_key.nil? true end def foreign_type return unless polymorphic? && %i[referenced_in belongs_to].include?(macro) association.inverse_type.try(:to_sym) || :"#{name}_type" end def foreign_inverse_of return unless polymorphic? && %i[referenced_in belongs_to].include?(macro) inverse_of_field.try(:to_sym) end def key_accessor case macro.to_sym when :has_many :"#{name.to_s.singularize}_ids" when :has_one :"#{name}_id" when :embedded_in, :embeds_one, :embeds_many nil else foreign_key end end def as association.as.try :to_sym end def polymorphic? association.polymorphic? && %i[referenced_in belongs_to].include?(macro) end def inverse_of association.inverse_of.try :to_sym end def read_only? false end def nested_options nested = nested_attributes_options.try { |o| o[name] } if !nested && %i[embeds_one embeds_many].include?(macro.to_sym) && !cyclic? raise <<~MSG Embedded association without accepts_nested_attributes_for can't be handled by RailsAdmin, because embedded model doesn't have top-level access. Please add `accepts_nested_attributes_for :#{association.name}' line to `#{model}' model. MSG end nested end def association? true end def macro association.try(:macro) || association.class.name.split('::').last.underscore.to_sym end def embeds? %i[embeds_one embeds_many].include?(macro) end private def inverse_of_field association.respond_to?(:inverse_of_field) && association.inverse_of_field end def cyclic? association.respond_to?(:cyclic?) ? association.cyclic? : association.cyclic end delegate :nested_attributes_options, to: :model, prefix: false delegate :polymorphic_parents, to: RailsAdmin::AbstractModel end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/active_record/object_extension.rb
lib/rails_admin/adapters/active_record/object_extension.rb
# frozen_string_literal: true module RailsAdmin module Adapters module ActiveRecord module ObjectExtension def assign_attributes(attributes) super if attributes end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/active_record/property.rb
lib/rails_admin/adapters/active_record/property.rb
# frozen_string_literal: true module RailsAdmin module Adapters module ActiveRecord class Property attr_reader :property, :model def initialize(property, model) @property = property @model = model end def name property.name.to_sym end def pretty_name property.name.to_s.tr('_', ' ').capitalize end def type if serialized? :serialized else property.type end end def length property.limit end def nullable? property.null end def serial? model.primary_key == property.name end def association? false end def read_only? model.readonly_attributes.include? property.name.to_s end private def serialized? model.type_for_attribute(property.name).instance_of?(::ActiveRecord::Type::Serialized) end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/adapters/active_record/association.rb
lib/rails_admin/adapters/active_record/association.rb
# frozen_string_literal: true module RailsAdmin module Adapters module ActiveRecord class Association attr_reader :association, :model def initialize(association, model) @association = association @model = model end def name association.name.to_sym end def pretty_name name.to_s.tr('_', ' ').capitalize end def type association.macro end def field_type if polymorphic? :polymorphic_association else :"#{association.macro}_association" end end def klass if options[:polymorphic] polymorphic_parents(:active_record, association.active_record.name.to_s, name) || [] else association.klass end end def primary_key return nil if polymorphic? value = case type when :has_one association.klass.primary_key else association.association_primary_key end if value.is_a? Array :id else value.to_sym end end def foreign_key if association.options[:query_constraints].present? association.options[:query_constraints].map(&:to_sym) elsif association.foreign_key.is_a?(Array) association.foreign_key.map(&:to_sym) else association.foreign_key.to_sym end end def foreign_key_nullable? return true if foreign_key.nil? || type != :has_many (column = klass.columns_hash[foreign_key.to_s]).nil? || column.null end def foreign_type options[:foreign_type].try(:to_sym) || :"#{name}_type" if options[:polymorphic] end def foreign_inverse_of nil end def key_accessor case type when :has_many, :has_and_belongs_to_many :"#{name.to_s.singularize}_ids" when :has_one :"#{name}_id" else if foreign_key.is_a?(Array) :"#{name}_id" else foreign_key end end end def as options[:as].try :to_sym end def polymorphic? options[:polymorphic] || false end def inverse_of options[:inverse_of].try :to_sym end def read_only? (klass.all.instance_exec(&scope).readonly_value if scope.is_a?(Proc) && scope.arity == 0) || association.nested? || false end def nested_options model.nested_attributes_options.try { |o| o[name.to_sym] } end def association? true end delegate :options, :scope, to: :association, prefix: false delegate :polymorphic_parents, to: RailsAdmin::AbstractModel end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/config/actions.rb
lib/rails_admin/config/actions.rb
# frozen_string_literal: true module RailsAdmin module Config module Actions class << self def all(scope = nil, bindings = {}) if scope.is_a?(Hash) bindings = scope scope = :all end scope ||= :all init_actions! actions = case scope when :all @@actions when :root @@actions.select(&:root?) when :collection @@actions.select(&:collection?) when :bulkable @@actions.select(&:bulkable?) when :member @@actions.select(&:member?) end actions = actions.collect { |action| action.with(bindings) } bindings[:controller] ? actions.select(&:visible?) : actions end def find(custom_key, bindings = {}) init_actions! action = @@actions.detect { |a| a.custom_key == custom_key }.try(:with, bindings) bindings[:controller] ? (action.try(:visible?) && action || nil) : action end def collection(key, parent_class = :base, &block) add_action key, parent_class, :collection, &block end def member(key, parent_class = :base, &block) add_action key, parent_class, :member, &block end def root(key, parent_class = :base, &block) add_action key, parent_class, :root, &block end def add_action(key, parent_class, parent, &block) a = "RailsAdmin::Config::Actions::#{parent_class.to_s.camelize}".constantize.new a.instance_eval(%( #{parent} true def key :#{key} end ), __FILE__, __LINE__ - 5) add_action_custom_key(a, &block) end def reset @@actions = nil end def register(name, klass = nil) if klass.nil? && name.is_a?(Class) klass = name name = klass.to_s.demodulize.underscore.to_sym end instance_eval %{ def #{name}(&block) action = #{klass}.new add_action_custom_key(action, &block) end }, __FILE__, __LINE__ - 5 end private def init_actions! @@actions ||= [ Dashboard.new, Index.new, Show.new, New.new, Edit.new, Export.new, Delete.new, BulkDelete.new, HistoryShow.new, HistoryIndex.new, ShowInApp.new, ] end def add_action_custom_key(action, &block) action.instance_eval(&block) if block @@actions ||= [] if action.custom_key.in?(@@actions.collect(&:custom_key)) raise "Action #{action.custom_key} already exists. Please change its custom key." else @@actions << action end end end end end end require 'rails_admin/config/actions/base' require 'rails_admin/config/actions/dashboard' require 'rails_admin/config/actions/index' require 'rails_admin/config/actions/show' require 'rails_admin/config/actions/show_in_app' require 'rails_admin/config/actions/history_show' require 'rails_admin/config/actions/history_index' require 'rails_admin/config/actions/new' require 'rails_admin/config/actions/edit' require 'rails_admin/config/actions/export' require 'rails_admin/config/actions/delete' require 'rails_admin/config/actions/bulk_delete'
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/config/sections.rb
lib/rails_admin/config/sections.rb
# frozen_string_literal: true require 'active_support/core_ext/string/inflections' require 'rails_admin/config/sections/base' require 'rails_admin/config/sections/edit' require 'rails_admin/config/sections/update' require 'rails_admin/config/sections/create' require 'rails_admin/config/sections/nested' require 'rails_admin/config/sections/modal' require 'rails_admin/config/sections/list' require 'rails_admin/config/sections/export' require 'rails_admin/config/sections/show' module RailsAdmin module Config # Sections describe different views in the RailsAdmin engine. Configurable sections are # list and navigation. # # Each section's class object can store generic configuration about that section (such as the # number of visible tabs in the main navigation), while the instances (accessed via model # configuration objects) store model specific configuration (such as the visibility of the # model). module Sections def self.included(klass) # Register accessors for all the sections in this namespace constants.each do |name| section = RailsAdmin::Config::Sections.const_get(name) name = name.to_s.underscore.to_sym klass.send(:define_method, name) do |&block| @sections ||= {} @sections[name] = section.new(self) unless @sections[name] @sections[name].instance_eval(&block) if block @sections[name] end end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/config/lazy_model.rb
lib/rails_admin/config/lazy_model.rb
# frozen_string_literal: true require 'rails_admin/config/model' module RailsAdmin module Config class LazyModel < BasicObject def initialize(entity, &block) @entity = entity @deferred_blocks = [*block] @initialized = false end def add_deferred_block(&block) if @initialized @model.instance_eval(&block) else @deferred_blocks << block end end def target @model ||= ::RailsAdmin::Config::Model.new(@entity) # When evaluating multiple configuration blocks, the order of # execution is important. As one would expect (in my opinion), # options defined within a resource should take precedence over # more general options defined in an initializer. This way, # general settings for a number of resources could be specified # in the initializer, while models could override these settings # later, if required. # # CAVEAT: It cannot be guaranteed that blocks defined in an initializer # will be loaded (and adde to @deferred_blocks) first. For instance, if # the initializer references a model class before defining # a RailsAdmin configuration block, the configuration from the # resource will get added to @deferred_blocks first: # # # app/models/some_model.rb # class SomeModel # rails_admin do # : # end # end # # # config/initializers/rails_admin.rb # model = 'SomeModel'.constantize # blocks from SomeModel get loaded # model.config model do # blocks from initializer gets loaded # : # end # # Thus, sort all blocks to execute for a resource by Proc.source_path, # to guarantee that blocks from 'config/initializers' evaluate before # blocks defined within a model class. unless @deferred_blocks.empty? @deferred_blocks. partition { |block| block.source_location.first =~ %r{config/initializers} }. flatten. each { |block| @model.instance_eval(&block) } @deferred_blocks = [] end @initialized = true @model end def method_missing(method_name, *args, &block) target.send(method_name, *args, &block) end def respond_to_missing?(method_name, include_private = false) super || target.respond_to?(method_name, include_private) end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/config/hideable.rb
lib/rails_admin/config/hideable.rb
# frozen_string_literal: true module RailsAdmin module Config # Defines a visibility configuration module Hideable # Visibility defaults to true. def self.included(klass) klass.register_instance_option :visible? do !root.try :excluded? end end # Reader whether object is hidden. def hidden? !visible end # Writer to hide object. def hide(&block) visible block ? proc { instance_eval(&block) == false } : false end # Writer to show field. def show(&block) visible block || true end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/config/has_groups.rb
lib/rails_admin/config/has_groups.rb
# frozen_string_literal: true require 'rails_admin/config/fields/group' module RailsAdmin module Config module HasGroups # Accessor for a group # # If group with given name does not yet exist it will be created. If a # block is passed it will be evaluated in the context of the group def group(name, &block) group = parent.groups.detect { |g| name == g.name } group ||= (parent.groups << RailsAdmin::Config::Fields::Group.new(self, name)).last group.tap { |g| g.section = self }.instance_eval(&block) if block group end # Reader for groups that are marked as visible def visible_groups parent.groups.collect { |f| f.section = self; f.with(bindings) }.select(&:visible?).select do |g| # rubocop:disable Style/Semicolon g.visible_fields.present? end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/lib/rails_admin/config/proxyable.rb
lib/rails_admin/config/proxyable.rb
# frozen_string_literal: true require 'rails_admin/config/proxyable/proxy' module RailsAdmin module Config module Proxyable def bindings Thread.current[:rails_admin_bindings] ||= {} Thread.current[:rails_admin_bindings][self] end def bindings=(new_bindings) Thread.current[:rails_admin_bindings] ||= {} if new_bindings.nil? Thread.current[:rails_admin_bindings].delete(self) else Thread.current[:rails_admin_bindings][self] = new_bindings end end def with(bindings = {}) RailsAdmin::Config::Proxyable::Proxy.new(self, bindings) end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false