Skip to content

Instantly share code, notes, and snippets.

@fxposter
Created October 20, 2015 10:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxposter/1682f9b667274dc4690d to your computer and use it in GitHub Desktop.
Save fxposter/1682f9b667274dc4690d to your computer and use it in GitHub Desktop.
Ruby quiz

Представьте что у вас есть некий класс API, который вы хотите использовать. Но вместо того чтобы всегда и везде писать api.method(args) вы хотите просто писать use_dsl { method(args) } внутри вашего обьекта.

Имея следующие классы, соответственно, API и его клиента реализуйте метод use_dsl так, чтобы получить такой вот результат:

client = Client.new(ThirdPartyAPI.new)

client.run_local_variable
# Output:
# a: 1
# No method `a`

client.run_instance_method
# Output:
# b: 2
# No method `b`

client.run_instance_variable
# Output:
# c: nil
# c: 3
# No method `c`
class ThirdPartyAPI
private
def a(value)
puts "a: #{value.inspect}"
end
def b(value)
puts "b: #{value.inspect}"
end
def c(value)
puts "c: #{value.inspect}"
end
end
class Client
def initialize(api)
@api = api
end
def run_local_variable
local_variable = 1
use_dsl do
a(local_variable)
end
begin
a(local_variable)
rescue NoMethodError
puts 'No method `a`'
end
end
def instance_method
2
end
def run_instance_method
use_dsl do
b(instance_method)
end
begin
b(instance_method)
rescue NoMethodError
puts 'No method `b`'
end
end
def run_instance_variable
@instance_variable = 3
use_dsl do |caller_frame|
c(@instance_variable)
c(caller_frame.eval { @instance_variable })
end
begin
c(@instance_variable)
rescue NoMethodError
puts 'No method `c`'
end
end
private
def use_dsl(&block)
# write code here
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment