Skip to content

Commit

Permalink
Add compile-time error when passing a raw Hash in to SaveOperation.cr…
Browse files Browse the repository at this point in the history
…eate/update. (#485)
  • Loading branch information
jwoertink authored Oct 16, 2020
1 parent b1759e0 commit 8a9cac8
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/avram/needy_initializer_and_save_methods.cr
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,30 @@ module Avram::NeedyInitializerAndSaveMethods
generate_save_methods({{ attribute_method_args }}, {{ attribute_params }})
end

macro hash_is_not_allowed_helpful_error(method)
{% raise <<-ERROR
You can't pass a Hash directly to #{method.id}. Instead pass named arguments, or convert the hash to params.
Try this...
* Pass named arguments - #{@type}.#{method.id}(title: "My Title")
* Convert hash to params - Avram::Params.new({"title" => "My Title"})
ERROR
%}
end

macro generate_create(attribute_method_args, attribute_params, with_params, with_bang)
def self.create{% if with_bang %}!{% end %}(
params : Hash, **named_args
)
{% if with_bang %}
{% else %}
yield nil, nil
{% end %}
hash_is_not_allowed_helpful_error(:create{% if with_bang %}!{% end %})
end

def self.create{% if with_bang %}!{% end %}(
{% if with_params %}params,{% end %}
{% for type_declaration in OPERATION_NEEDS %}
Expand Down Expand Up @@ -110,6 +133,18 @@ module Avram::NeedyInitializerAndSaveMethods
end

macro generate_update(attribute_method_args, attribute_params, with_params, with_bang)
def self.update{% if with_bang %}!{% end %}(
record : T,
params : Hash,
**named_args
)
{% if with_bang %}
{% else %}
yield nil, nil
{% end %}
hash_is_not_allowed_helpful_error(:update{% if with_bang %}!{% end %})
end

def self.update{% if with_bang %}!{% end %}(
record : T,
{% if with_params %}with params,{% end %}
Expand Down

0 comments on commit 8a9cac8

Please # to comment.