Skip to content

Instantly share code, notes, and snippets.

@Schniz
Last active September 18, 2018 23:51
Show Gist options
  • Select an option

  • Save Schniz/f19188710f74ee07d0e3767554e5a1a6 to your computer and use it in GitHub Desktop.

Select an option

Save Schniz/f19188710f74ee07d0e3767554e5a1a6 to your computer and use it in GitHub Desktop.
add typed `init_with` to Crystal Crecto models

Usage

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!
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