class User < Crecto::Model
schema "users" do
field :name, String
end
end
user = User.init_with(name: "hello") # doesn't fail
user = User.init_with(other_param: "hello") # can't compile, `other_param=` isn't defined on a User instance!
Last active
September 18, 2018 23:51
-
-
Save Schniz/f19188710f74ee07d0e3767554e5a1a6 to your computer and use it in GitHub Desktop.
add typed `init_with` to Crystal Crecto models
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Crecto::Model | |
| macro init_with(**args) | |
| {{@type}}.new.tap do |item| | |
| {% for setter, value in args %} | |
| {% raise "#{@type} doesn't have a setter called '#{setter}'" unless @type.methods.map(&.name.stringify).includes?("#{setter}=") %} | |
| item.{{setter.id}} = {{value}} | |
| {% end %} | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment