-
Notifications
You must be signed in to change notification settings - Fork 5
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: Dynamic methods in ruby #180
Open
nitinrajkumar451
wants to merge
5
commits into
main
Choose a base branch
from
dynamic-method-in-ruby
base: main
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a128293
ADD: Dynamic methods in ruby
nitinrajkumar451 5af42eb
Merge branch 'main' into dynamic-method-in-ruby
2KAbhishek c50837a
Update README.md
nitinrajkumar451 ba6a519
Update content/blog/dynamic-method.md
nitinrajkumar451 72ea188
Merge branch 'main' into dynamic-method-in-ruby
2KAbhishek File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
+++ | ||
title = "Dynamic method in ruby" | ||
slug = "dynamic-method" | ||
date = 2023-10-27T13:31:36+05:30 | ||
image = "/images/2023/10/methodmissing.jpg" | ||
draft = false | ||
authors = ["Nitin Rajkumar"] | ||
description = "Dynamic and ghost methods in ruby" | ||
tags = ["Software Craftsmanship", "GraphQL"] | ||
categories = ["Software Craftsmanship", "Ruby", "Dynamic Dispatch", "Ghost Methods"] | ||
type = "" | ||
+++ | ||
|
||
In Ruby, the dynamic nature of method dispatch is one of its key features. Method calls are resolved at runtime based on the actual type of the object. This flexibility allows for polymorphic and dynamic behavior | ||
#### Dynamic Dispatch | ||
```ruby | ||
class Number | ||
def square(argument) | ||
argument ** 2 | ||
end | ||
def cube(argument) | ||
argument ** 3 | ||
end | ||
end | ||
number = Number.new | ||
number.square(3) #=> 9 | ||
``` | ||
|
||
Method can be called using dot notation but this restricts making the method call being dynamic. | ||
There is another way to call a method that is using `send`. It accepts method name and it's arguments as arguments. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. instead of "it's arguments as arguments" "the method's arguments as it own arguments" |
||
```ruby | ||
number.send(:square, 3) #=> 9 | ||
``` | ||
Since the method name is an argument it can be replaced by any method name during runtime. | ||
```ruby | ||
puts "Enter a number:" | ||
user_input = gets.chomp | ||
puts "Enter the method name:" | ||
method_name = gets.chomp | ||
number.send(method_name.to_sym, 4) #=> 16 | ||
|
||
``` | ||
`to_sym is used to convert string to symbol but method name can be passed as string.` | ||
Using send to dispatch a method has a downside when it comes to privacy concerns as it invokes even a private method of the class without throwing an error. | ||
This can be prevented using by using `public_send`. | ||
|
||
We can not only call methods during runtime but also define methods during runtime. | ||
|
||
#### Dynamic Methods | ||
A method can be defined using `define_method` at the run time. | ||
```ruby | ||
class Number | ||
define_component(method_name, argument, power) | ||
define_method(method_name) do |argument, power| | ||
argument ** power | ||
end | ||
end | ||
end | ||
number = Number.new | ||
number.define_component(square,4, 2) #=> 16 | ||
number.define_component(cube,4, 3) #=> 64 | ||
``` | ||
|
||
There is another way of defining methods dynamically using method_missing. | ||
|
||
### Ghost Method | ||
|
||
What happens when you call a method on an object that is not yet defined. A method missing error is displayed. What happens internally is ruby goes right and up and checks from the ancestor chain up till `BasicObject` and when the method is not found it transfers the call to `method_missing` in `BasicObject` class, which returns `NoMethodError`. | ||
nitinrajkumar451 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```ruby | ||
class Book | ||
end | ||
book = Book.new | ||
book.author | ||
#=>undefined method `author' for #<Book:0x00005585e38e9720> (NoMethodError) | ||
``` | ||
We can override this method and return what we want to. | ||
```ruby | ||
class Book | ||
def method_missing(method, args) | ||
"All missing methods return this string" | ||
end | ||
end | ||
book = Book.new | ||
book.author | ||
#=>"All missing methods return this string" | ||
|
||
``` | ||
`method_missing` comes with huge advantage when there are many methods with similar definition. It saves the time of writing them and testing them independently. | ||
|
||
#### Cons | ||
1. Readability and maintainability of code. | ||
2. Security issues arise when method name is taken from input. | ||
3. When the method which is supposed to be missing is found in ancestors chain. | ||
4. Debugging would be complex. | ||
|
||
#### Conclusion | ||
It is worth noting that while these dynamic features of ruby are powerful they should be used with caution, considering trade-offs. | ||
|
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the class.method("method_name").call should also be included here and a one liner about how it differs from send