Skip to content

Instantly share code, notes, and snippets.

@brianknapp
Last active December 16, 2015 02:29
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 brianknapp/5363187 to your computer and use it in GitHub Desktop.
Save brianknapp/5363187 to your computer and use it in GitHub Desktop.
Objective-Ruby? This is an attempt add type checking and more descriptive named parameters to ruby. This might make it in to Obvious at some point...
module ObjectiveRuby
class << self
def included(base)
base.extend ClassMethods
end
end
module ClassMethods
def obj method, input = {}, &block
define_method(method) do |method_input = {}|
block_input = {}
method_input.each do |k,v|
new_key = k.to_s.sub!(/(with_|and_)/, '').to_sym
if input[new_key].nil?
raise ArgumentError.new "invalid input field #{k}"
end
unless v.is_a? input[new_key]
raise ArgumentError.new "invalid type for #{new_key} expected #{input[new_key]}"
end
block_input[new_key] = v
end
block.call block_input
end
end
def objr method, input = {}, &block
define_method(method) do |method_input = {}|
block_input = {}
method_input.each do |k,v|
if input[k].nil?
raise ArgumentError.new "invalid input field #{k}"
end
unless v.is_a? input[k][1]
raise ArgumentError.new "invalid type for #{new_key} expected #{input[new_key]}"
end
block_input[input[k][0]] = v
end
block.call block_input
end
end
end
end
class Foo
include ObjectiveRuby
@stuff = 12
obj :execute, foo: String, bar: Fixnum do |input|
puts "foo: #{input[:foo]}"
puts "bar: #{input[:bar]}"
puts "stuff: #{@stuff}"
end
obj :fun do
puts 'fun!'
end
objr :test, with_foo: [:foo, String], before_when?: [:some_time, String] do |input|
puts "foo: #{input[:foo]}"
puts "some time: #{input[:some_time]}"
end
end
f = Foo.new
f.test with_foo: 'hi', before_when?: 'now'
f.execute with_foo: 'hi', and_bar: 1
f.fun #this is pointless, but fun
#f.execute with_foo: 'hi' # this will fail with nil
#f.execute with_foo: nil, and_bar: 1 # this will fail with nil
@brianknapp
Copy link
Author

This experiment has officially begot the gem 'objective-ruby' - https://rubygems.org/gems/objective-ruby

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment