Back to Skills

ruby-metaprogramming

verified

Use when working with Ruby metaprogramming features including dynamic method definition, method_missing, class_eval, define_method, and reflection.

View on GitHub

Marketplace

han

TheBushidoCollective/han

Plugin

jutsu-ruby

Technique

Repository

TheBushidoCollective/han
60stars

jutsu/jutsu-ruby/skills/ruby-metaprogramming/SKILL.md

Last Verified

January 24, 2026

Install Skill

Select agents to install to:

Scope:
npx add-skill https://github.com/TheBushidoCollective/han/blob/main/jutsu/jutsu-ruby/skills/ruby-metaprogramming/SKILL.md -a claude-code --skill ruby-metaprogramming

Installation paths:

Claude
.claude/skills/ruby-metaprogramming/
Powered by add-skill CLI

Instructions

# Ruby Metaprogramming

Master Ruby's powerful metaprogramming capabilities to write code that writes code. Ruby's dynamic nature makes it exceptionally good at metaprogramming.

## Dynamic Method Definition

### define_method

```ruby
class Person
  [:name, :age, :email].each do |attribute|
    define_method(attribute) do
      instance_variable_get("@#{attribute}")
    end

    define_method("#{attribute}=") do |value|
      instance_variable_set("@#{attribute}", value)
    end
  end
end

person = Person.new
person.name = "Alice"
puts person.name  # "Alice"
```

### class_eval and instance_eval

```ruby
# class_eval - Evaluates code in context of a class
class MyClass
end

MyClass.class_eval do
  def hello
    "Hello from class_eval"
  end
end

puts MyClass.new.hello

# instance_eval - Evaluates code in context of an instance
obj = Object.new
obj.instance_eval do
  def greet
    "Hello from instance_eval"
  end
end

puts obj.greet
```

### module_eval

```ruby
module MyModule
end

MyModule.module_eval do
  def self.info
    "Module metaprogramming"
  end
end

puts MyModule.info
```

## Method Missing

### Basic method_missing

```ruby
class DynamicFinder
  def initialize(data)
    @data = data
  end

  def method_missing(method_name, *args)
    if method_name.to_s.start_with?("find_by_")
      attribute = method_name.to_s.sub("find_by_", "")
      @data.find { |item| item[attribute.to_sym] == args.first }
    else
      super
    end
  end

  def respond_to_missing?(method_name, include_private = false)
    method_name.to_s.start_with?("find_by_") || super
  end
end

users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 }
]

finder = DynamicFinder.new(users)
puts finder.find_by_name("Alice")  # {:name=>"Alice", :age=>30}
```

### Const Missing

```ruby
class DynamicConstants
  def self.const_missing(const_name)
    puts "Constant #{const_name} not found, creating it..."
    const_set(const_name, "Dynamic value for #{const_name}")
  end
end

puts Dynamic

Validation Details

Front Matter
Required Fields
Valid Name Format
Valid Description
Has Sections
Allowed Tools
Instruction Length:
8842 chars