Locker
I often code when going to sleep. I think about a problem or a subject and how I would attack it.. solve it.
In another project, I had the need for Ruby to be “temporary typed”. I can’t do that! But I can do something that works for me.
This is not the code.. it’s the instance:
require 'mw_locker.rb'
# first all variables using this class must be defined.
# They have a type (or types).
# They can use the 'filter'-property.. a Range or Array of values.
# Also a 'regex'-property.
# finally an optional block (or 'proc'-property of Proc or Lambda)
#
# It's mainly a setter/getter. All checks and procs are done when set.
X = Locker::TypeCreate.new {
name(String) {|v| v.to_s }
age Integer, filter: (1..100)
name_age(Array) {|s| s.split(':') }
to_bin(String) {|i| i.to_s(2) }
# using proc: you can add proc or lambda
# to_bin String, proc: ->(i) {i.to_s(2)}
# to_bin String, proc: proc {|i| i.to_s(2)}
# filter can be Range or Array (of allowed values)
# Range can be inclusive or not.
regplate String, regex: /^[A-ZÅÄÖ]{3}\s*\d{2}[0-9A-ZÅÄÖ]$/i
testa [TrueClass, FalseClass]
result [String, Integer, NilClass]
copy(String) {|v| X.name = v }
koko :NoTypecheck
person(:NoTypecheck) {|stc| stc.new(X.name, X.age) }
}.__parse
# -------------------------------------------------------------
X.age = 100
p X.age # => 100
X.name_age = 'Olle:21'
p X.name_age # => ["Olle", 21]
# X.age = 101 # => Exceptions::LockerFilterError
X.to_bin = 7
p X.to_bin # => "111"
h = {name: 'Otto', age: 34}
X.result = h[:name] # String is allowed
X.result = h[:age] # Integer is allowed
X.result = h[:city] # nil is allowed
# p X.apa # => Exceptions::LockerKeyError
X.copy = 'Stig'
p X.copy # => "Stig"
p X.name # => "Stig"
X.regplate = 'KKC 338'
X.regplate = 'bbo33z'
begin X.regplate = 'ABC-123'
rescue Exceptions::LockerRegexError; end
# .name converts any value to String
p X.name = 8
p X.name # => "8"
# .koko do not check for type
X.koko = 3.14
X.koko = 8
X.koko = :hejsan
# .person do no type-checking
# ..recieves a Struct and runs the block
# setting .name and .age
X.name = :Heliga_Lurban
# populates the struct with .name and .age
X.person = Struct.new(:name, :age)
p '%s is %s years old.' % [X.person.name, X.person.age]
The thing that made me want his came from this:
X = Locker::TypeCreate.new {
key Symbol
}.__parse
# inside a method_missing(key)
X.key = key
if X.key[/=$/]
X.key = X.key[..-2]
# do something with the key
end
I would get a warning.. EY! key just changed from Symbol to String!!!
Because without that warning.. I’d still have a key. And it would work on a Hash. I would have {some_key: ‘important’, ‘some_key’: ‘shit’}
The source-code is still a bit ugly (I had this idea the night before yesterday.. so I just worked on it 2hrs yesterday and some fixes today). Anyway.. too ugly still to show. But I think most people who used Ruby for more than a year.. would realize what the code would look like.