lib/active_text/base.rb in active_text-0.0.4 vs lib/active_text/base.rb in active_text-0.0.5

- old
+ new

@@ -11,55 +11,61 @@ options[:context_lines] ||= 3 options[:comment] ||= /\/\// options[:context] ||= "(^(?:#{options[:comment]}\s@.*#{options[:eol]}){#{options[:context_lines]}})" @options = options - scan + # instantiate all variables + @text.scan(/^\${1}(.+): .+;/).flatten.each do |variable_name| + if has_context?(variable_name) + variable = ActiveText::Variable.new(variable_name, context_of(variable_name), @options[:comment]) + @variables.merge!({variable_name.to_sym => variable}) + end + end end def update_attributes(args) args.each do |k, v| - send(k) # Instantiate it, so it will exist in @variables - @variables[k].value = v unless @variables[k].nil? || v.nil? + send "#{k.to_s}=", v end end # Used to update the text - def apply + def render @variables.each do |key, var| @text.gsub!(/^\$#{key}: .+;/, %Q($#{key}: #{var.value};)) end @text end - def attributes - @variables + def [](key) + variable = @variables[key] + {:name => variable.name, :description => variable.description, :value => variable.value, :kind => variable.kind} end - protected - - # scans though the text and instantiates all the variables in @variables - def scan - @text.each do |string| - string =~ /^\${1}([a-zA-Z0-9_]+):.+;/ - @variables[$1] = ActiveText::Variable.new($1, context_of($1), @options[:comment]) if $1 + def attributes + h = {} + @variables.each do |key, variable| + h.merge!({key => variable.value}) end + h end - # Whenever a variable is requested for, it falls into this. - def method_missing(method_name) - if method_name.to_s =~ /[\w]+/ - context = context_of(method_name) + protected - # If there's no context (no variable with the proper - # commented metadata), then it should not be accessible - # and it won't be accessible - if context.nil? || context == "" - nil + # Whenever a variable is requested for, it falls into this. + def method_missing(method_name, *args, &block) + attr_key = method_name.to_s.sub(/\=$/, '').to_sym + variable = @variables[attr_key] + if variable + if method_name.to_s =~ /\=$/ + value = args[0] + variable.value = value unless value.nil? else - @variables[method_name] ||= ActiveText::Variable.new(method_name, context, @options[:comment]) + variable.value end + else + raise NoMethodError, "Variable does not exist" end end # Works this way: http://rubular.com/r/jWSYvfVrjj # From http://rubular.com/r/jWSYvfVrjj @@ -67,8 +73,13 @@ def context_of(s) regexp = /.*\${1}#{s}:.*;[#{@options[:eol]}]*/ @text =~ /^#{@options[:context]}(#{regexp})/ before, match = $1, $2 "#{before}#{match}" + end + + def has_context?(s) + context = context_of(s) + !(context.nil? || context == "") end end end