Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fran-worley
Last active March 28, 2017 19:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fran-worley/8da7d06f047c8ac512da9a195a37473f to your computer and use it in GitHub Desktop.
Save fran-worley/8da7d06f047c8ac512da9a195a37473f to your computer and use it in GitHub Desktop.
Some Reform/dry-v examples
class FieldForm < Reform::Form
property :key
collection :field_options, form: FieldOptionForm
validation do
configure do
option :form # include this line if you want access to your form in predicates
config.messages_file = 'config/error_messages.yml' # if you define any custom predicates you must provide a message for them
# custom predicates must be defined in the configure block
def uniq_key?(value)
# here I access the model id to check if the fields key is unique.
# in a predicate you've got access to your form.
Field.where.not(id: form.model.id).where(key: value).empty?
end
end
required(:key).filled(:uniq_key?)
requried(:field_options).filled(min_size?: 1)
end
end
class ExampleTwoForm < Reform::Form
validation do
configure do
option :form # include this line if you want access to your form in predicates
config.messages_file = 'config/error_messages.yml' # if you define any custom predicates you must provide a message for them
def within_client_scope?(value)
# here I am making sure that the profile_id is the id of a profile in the current organisation.
# the only time this could fail is if the user hacked his HTML form params, but still worth checking.
!form.model.organisation.profiles.where(id: value).empty?
end
end
required(:profile_id).filled(:within_client_scope?)
end
end
class ExampleUserForm < Reform::Form
validation :authenticate_current_password do
configure do
option :form # include this line if you want access to your form in predicates
config.messages_file = 'config/error_messages.yml' # if you define any custom predicates you must provide a message for them
def account_authenticated?(password)
form.model.authenticate(password)
end
end
required(:current_password).filled(:account_authenticated?)
end
end
@fran-worley
Copy link
Author

I would love to be able to inject the current user into my schemas as that would open a world of possibilities for permission based validation. At the moment it isn't such an issue as we have a couple of distinct roles which have their own forms to ensure that only attributes that they can change are available.
However moving forward we would like to have user customisable permissions and in this case we would need to be able to define rules whereby a record is invalid if certain attributes were changed based on the users permissions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment