Advertisement
swarley

rubyserif

Mar 14th, 2012
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.17 KB | None | 0 0
  1. module JavaScript
  2.     class Object
  3.         def initialize(hash={}, constants=[]) #Put keys into constants that you want to be read only
  4.             @hash,@constants=hash,constants
  5.         end
  6.         def method_missing(name, *args, &block)
  7.             if name.to_s =~ /=$/
  8.                 if @constants.include? name.to_s.sub(/=/,'').to_sym
  9.                     raise Exception.new "Cannot modify object constant - #{name.to_s.sub(/=/,'')}"
  10.                 end
  11.                 @hash[name.to_s.sub(/=/,'').to_sym] = ((args==[]) ? ((block.nil?) ? nil : block) : args[0])
  12.             elsif name =~ /^\/(.+?)$/
  13.                 method(:"/").call($1.to_sym) #/
  14.             else
  15.                 return @hash[name]
  16.             end
  17.         end
  18.         define_singleton_method(:"/") do |args=:elements|
  19.             case args
  20.             when :elements
  21.                 return @hash.keys
  22.             when :constants
  23.                 return @constants
  24.             else
  25.                 return nil
  26.             end
  27.         end
  28.     end
  29.    
  30.     class Function
  31.         def initialize(&code)
  32.             @code = code
  33.         end
  34.        
  35.         def [](*args)
  36.             i='a'; string=''
  37.             while(arg = args.shift)
  38.                 @temp = {}
  39.                 eval "@temp[:#{i}] = arg"
  40.                 string << ", @temp[:#{i}]"
  41.                 i.next!
  42.             end
  43.             string.sub!(/\,/,'')
  44.             eval "@code.call #{string}"
  45.             @temp = nil
  46.         end
  47.     end
  48. end
  49.  
  50. __END__
  51.  
  52. [1] pry(main)> require 'rubyserif'
  53. => true
  54. [2] pry(main)> k = JavaScript::Object.new({:foo => 'bar', :constant => 'not easily changed'}, [:constant])
  55. => #<JavaScript::Object:0x000000024536c8
  56.  @constants=[:constant],
  57.  @hash={:foo=>"bar", :constant=>"not easily changed"}>
  58. [3] pry(main)> k.foo
  59. => "bar"
  60. [4] pry(main)> k.foo = 'foobar'
  61. => "foobar"
  62. [5] pry(main)> k.new_element = :hello
  63. => :hello
  64. [6] pry(main)> k/:elements
  65. => [:foo, :constant, :new_element]
  66. [7] pry(main)> k/:constants
  67. => [:constant]
  68. [8] pry(main)> k.constant = 'lol'
  69. Exception: Cannot modify object constant - constant
  70. from /var/lib/gems/1.9.1/gems/rubyserif-0.1/lib/rubyserif.rb:11:in `method_missing'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement