Skip to content

Commit

Permalink
Move field requireness logic to Field::Base
Browse files Browse the repository at this point in the history
Given that application helpers are available throughout the app and the
highly specific nature of some of the actions required to determine
whether or not a field is required, moving that logic to Field::Base
feels more appropriate.

This also allows us to add more complex checks to determine whether or
not a field is required without exposing that logic everywhere in the
application.
  • Loading branch information
Jonas Meinerz committed Oct 23, 2020
1 parent a5d695d commit cbf9fd0
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 28 deletions.
17 changes: 1 addition & 16 deletions app/helpers/administrate/application_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,7 @@ def render_field(field, locals = {})
end

def requireness(field)
required_field?(field) ? "required" : "optional"
end

def required_field?(field)
has_presence_validator?(field.resource.class, field.attribute)
end

def has_presence_validator?(resource_class, field_name)
validators_on(resource_class, field_name).
any? { |v| v.class == ActiveRecord::Validations::PresenceValidator }
end

def validators_on(resource_class, field_name)
return [] unless resource_class.respond_to?(:validators_on)

resource_class.validators_on(field_name)
field.required? ? "required" : "optional"
end

def dashboard_from_resource(resource_name)
Expand Down
8 changes: 8 additions & 0 deletions lib/administrate/field/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ def to_partial_path
"/fields/#{self.class.field_type}/#{page}"
end

def required?
return false unless resource.class.respond_to?(:validators_on)

resource.class.validators_on(attribute).any? do |v|
v.class == ActiveRecord::Validations::PresenceValidator
end
end

attr_reader :attribute, :data, :options, :page, :resource
end
end
Expand Down
12 changes: 0 additions & 12 deletions spec/helpers/administrate/application_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,6 @@
end
end

describe "#has_presence_validator?" do
it "returns true if field is required" do
required = has_presence_validator?(Blog::Post, :title)
expect(required).to eq(true)
end

it "returns false if field is not required" do
required = has_presence_validator?(Blog::Post, :publish_at)
expect(required).to eq(false)
end
end

describe "#sort_order" do
it "sanitizes to ascending/descending/none" do
expect(sort_order("asc")).to eq("ascending")
Expand Down

0 comments on commit cbf9fd0

Please sign in to comment.