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

Add compile-time catches for common method call mistakes with attributes #738

Merged
merged 3 commits into from
Oct 9, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/avram/attribute.cr
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,64 @@ class Avram::Attribute(T)
add_error("is invalid")
end
end

# These methods may accidentally get called on attributes
# inside of operations. Since these methods don't exist,
# chances are, you meant to call them on the value.
# ```
# username.to_s
# # VS
# username.value.to_s
# ```
def to_s
call_value_instead_error_message(".to_s")
end

# NOTE: to_s(io : IO) is used when passing an object
# in to string interpolation. Don't override that method.
def to_s(time_format : String)
call_value_instead_error_message(".to_s(...)")
end
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think these are a great addition. If there's one mistake I make all the time it's calling these methods accidentally.

This specific overload makes me a bit nervous because of the way the name of the string parameter would confuse someone who happened upon this error message through some secondary path that had nothing to do with a time format.

What if the stringified method suggestion in the error message is just .to_s(...) instead? That seems like it would lead people down an almost identical path without lending confusion where they landed here without doing anything with time formats.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like that 👍 Makes sense.


def to_i
call_value_instead_error_message(".to_i")
end

def to_i32
call_value_instead_error_message(".to_i32")
end

def to_i64
call_value_instead_error_message(".to_i64")
end

def to_f
call_value_instead_error_message(".to_f")
end

def to_f64
call_value_instead_error_message(".to_f64")
end

def [](key)
call_value_instead_error_message(".[key]")
end

def []?(key)
call_value_instead_error_message(".[key]?")
end

macro call_value_instead_error_message(method)
{% raise <<-ERROR

The #{method.id} method should not be called directly on attributes (#{@type}).
Did you mean to call it on the value property?

Try this...

▸ attribute.value#{method.id}

ERROR
%}
end
end