Skip to content

Instantly share code, notes, and snippets.

@fran-worley

fran-worley/Example 1

Last active Mar 28, 2017
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@fran-worley fran-worley commented May 12, 2016

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