Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allows attribute type to be specified as Array[Person] #68

Closed
wants to merge 1 commit into from

Conversation

krisleech
Copy link
Sponsor

Opening this PR to start discussion.

I would like to be able to do this:

class Person
  attr_reader :name

  def initalize(attributes); 
    @name = attributes.fetch(:name)
  end
end

class MyForm
  include Lotus::Validations

  attribute :people, type: Array[Person]
end

form = MyForm.new(people: [{ name: 'Kris', name: 'Lindsey' }]
form.people.first.name # => 'Kris'
form.people.all? { |p| p.is_a?(Person) } # => true

This PR is a quick hack, there are no tests. If you think it is an okay direction - handling a coercer which is a one element Array, as a special case - then I will submit a proper PR with tests.

In theory you could also support something like type: Array[Person, Fruit, Mineral] if the collection was not homogeneous but can't see a usecase for this and it would probably be confusing.

coerce each element of Array to the given type.
@krisleech
Copy link
Sponsor Author

@duncanita
Copy link

Hi, I have problem with validation of params like this

{ users: [ { name: 'bob'}, {name: 'Joe'}] }

@jodosha
Copy link
Member

jodosha commented Oct 16, 2015

@krisleech @duncanita I've looked closely at this issue and for me is a 👎

What would that syntax mean in terms of code? Would that Array[<Object>] be an object that could be validated (respond to #valid?) or is just a type notation?

If it's the first case, how to handle the error messages with the "dot syntax" for attributes (eg signup.user.address.city)? If you receive { people: [ {name: 'Alice'}, { name: '' } ]}, how to return the error message for the single wrong entry?

If it's just a type notation, should the validation pass if we're able to coerce it? Imagine we have a validation like this: dates: Array[Date], would data like: { dates: ['2020-01-01'] } be valid? Theoretically yes, but it lacks of flexibility because you may also want to add further validation rules.

I think this should be implemented via a custom validation. See #72

@jodosha jodosha closed this Oct 16, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants