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

Custom type for from_hash #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Custom type for from_hash #2

wants to merge 1 commit into from

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.

1 participant