Skip to content

Conversation

@ksss
Copy link
Owner

@ksss ksss commented May 31, 2016

This is an experimental PR for review.

You can make custom class for from_hash method.

Example.

class TypeStruct
  class PresentArrayOf < ArrayOf
    PresentError = Class.new(StandardError)
    def ===(ary)
      return false unless ary.empty?.!
      super
    end

    def try_convert(key, value, errors)
      raise PresentError, "array must not be empty" unless 0 < value.length
      super
    end
  end
end

Foo = TypeStruct.new(
  foo: TypeStruct::PresentArrayOf.new(String)
)

Foo.from_hash({foo: []})
#=> TypeStruct::PresentArrayOf::PresentError: must not be empty

Foo.from_hash({foo: [1]})
#=> TypeStruct::MultiTypeError
#=> TypeStruct#foo expect String got 1

Foo.from_hash({foo: ["bar"]})
#=> #<Foo foo=["bar"]>

@ksss ksss force-pushed the custom_type_of branch from 43aa6a1 to ebe0e6f Compare May 31, 2016 06:03
@ksss
Copy link
Owner Author

ksss commented Jul 9, 2016

current issues

  • I don't like try_convert
  • Not simple

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants