Skip to content

Instantly share code, notes, and snippets.

@alieseparker
Created November 11, 2014 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alieseparker/15302981a1c4fc46c92d to your computer and use it in GitHub Desktop.
Save alieseparker/15302981a1c4fc46c92d to your computer and use it in GitHub Desktop.
Ruby Meta Programming
# First a primer on Meta Programming:
Meta programming happens all the time under the surface. You are meta programming whenever you are writting code that operates on code rather then data. A great example in Ruby is anytime you use a generator, you are using a bit of code to write new code. This is metaprogramming. But of course we can use meta programming outside of just using a generator. A great example is the String Class, out of the box it doesn't have a way to split a sentence into individual words within an array. We can reopen the String class and write our own method in.
```Ruby
Class String
def split_words
split(' ')
end
end
```
Pretty cool huh? Well... Lets take a look at another example inside a gem file.
This code is taken right out of minitest-capybara.
```Ruby
module Minitest
module Features
module DSL
include AcceptanceSpec
##
# describe is 'defined' in Object
# therefore it is available anywhere
# so that allows us to simply
# alias feature to describe.
alias :feature :describe
end
end
module Spec::DSL
# here we tell ruby that when we include the Spec::DSL we want to be able to use some different alias's to allow us to be more
# transparent with our code. We redifine :it to work with :scenario and so on
alias :scenario :it
alias :background :before
alias :given :let
end
end
Object.send(:include, Minitest::Features::DSL)
```
So. As you can see we can use meta programming for all sorts of things! Another example, we could re-open the Array Class and write
our own sorting algorithms and then we would have access to that code for future use. Pretty awesome huh?
## Contributions:
- http://rubymonk.com/learning/books/2-metaprogramming-ruby/chapters/32-introduction-to-metaprogramming/lessons/75-being-meta#solution3969
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment