Skip to content

Commit

Permalink
Merge pull request maxdemarzi#104 from wcamarao/dev
Browse files Browse the repository at this point in the history
Make ruby regex shareable with javascript
  • Loading branch information
Wagner Camarao committed Feb 5, 2014
2 parents 0026a01 + 01d5342 commit 998a419
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/deja.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
require 'neo4j-cypher/neography'

require 'active_model'
require 'active_support'
require 'active_support/core_ext'

require 'oj'
require 'yaml'
Expand Down
30 changes: 28 additions & 2 deletions lib/deja/schema_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,45 @@ def inspect_attributes
attrs
end

def inspect_validations
def inspect_validations(for_json = false)
validators.inject({}) do |memo, validator|
if validator.respond_to? :attributes
validator.attributes.each do |attr|
memo[attr] ||= {}
memo[attr][validator.kind] = validator.options

if for_json
options = validator.options.deep_dup
options[:with] = json_regexp(options[:with]) if options.has_key?(:with)
memo[attr][validator.kind] = options
else
memo[attr][validator.kind] = validator.options
end

end
memo
else
memo
end
end
end

# The following method (extracted from rails) adds support for sharing ruby regular expressions with javascript via JSON.

# For more details, see http://www.edgerails.info/2013/1/21/whats-new-55/ and
# https://github.com/rails/rails/blob/b67043393b5ed6079989513299fe303ec3bc133b/actionpack/lib/action_dispatch/routing/inspector.rb#L42

def json_regexp(regexp)
str = regexp.inspect.
sub('\\A', '^').
sub('\\Z', '$').
sub('\\z', '$').
sub(/^\//, '').
sub(/\/[a-z]*$/, '').
gsub(/\(\?#.+\)/, '').
gsub(/\(\?-\w+:/, '(').
gsub(/\s/, '')
Regexp.new(str).source
end
end
end
end

0 comments on commit 998a419

Please sign in to comment.