Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

ruby refinement import dynamic methods

module DefineMethodModule
  5.times do |i|
    # Methods defined with `define_method` or `define_singleton_method`
    # do not count as methods defined in Ruby code.
    #
    # As such they can't be imported in Refinements!
    define_method :"define_method_#{i}" do
      puts "its me, the new define_method_#{i}!"
    end
  end
end

module StringEvalModule
  5.times do |i|
    # The only way to import dynamically generated methods
    # to Refinements is to construct a String with Ruby code
    # that defines the method and pass it to `eval` or `instance_eval`
    eval <<~RUBY
    	def string_eval_#{i}
        	puts "its me, the new string_eval_#{i}!"
        end
    RUBY
  end
end

module SomeRefinement
  refine String do
    # import_methods DefineMethodModule
    # the line above would result in an error
    #=> in `import_methods': Can't import method which is not defined with Ruby code
    import_methods StringEvalModule
  end
end

using SomeRefinement
string = ""
string.string_eval_3 #=> its me, the new string_eval_3!
Comment

PREVIOUS NEXT
Code Example
Ruby :: rails delete link 
Ruby :: rails trackable to devise 
Ruby :: rails get current database name 
Ruby :: get current year in ruby 
Ruby :: ruby get substring between two characters 
Ruby :: ruby array includes 
Ruby :: rspec parallel tests 
Ruby :: find path of module in ruby 
Ruby :: ruby read file 
Ruby :: contains ruby array 
Ruby :: ruby catch all exceptions 
Ruby :: rails remove model 
Ruby :: edit file terminal mac24 
Ruby :: conditional operator in ruby 
Ruby :: how to link to with font awesome rails 
Ruby :: shopify: how to show percentage discount saved 
Ruby :: create a new hash from existing hash ruby 
Ruby :: rails convert image to base64 
Ruby :: ruby compiler 
Ruby :: rails params require check exists 
Ruby :: string to hash ruby 
Ruby :: rails server not updating 
Ruby :: ruby shorthand if 
Ruby :: ruby array loop 
Ruby :: convert ruby hash to json string 
Ruby :: activerecord exclude 
Ruby :: render to string rails 
Ruby :: add key and value to first spot in hash ruby 
Ruby :: ruby global property from object 
Ruby :: save rails c output 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =