yaml_strings 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in yaml_string.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Jonathan R. Wallace
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # YamlStrings
2
+
3
+ Converts a YAML file, specifically the ones typically used for locale and
4
+ translation files in Rails, to an old style Apple ASCII Property List,
5
+ http://bit.ly/old_style_ascii_property_list
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ gem 'yaml_strings'
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install yaml_strings
20
+
21
+ ## Usage
22
+
23
+ $ rake yaml_strings:yaml_to_strings YAML_FILE=<path_to_file> > your_file_name.strings
24
+
25
+ ## Contributing
26
+
27
+ 1. Fork it
28
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
29
+ 3. Commit your changes (`git commit -am 'Added some feature'`)
30
+ 4. Push to the branch (`git push origin my-new-feature`)
31
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+ require "rspec/core/rake_task"
4
+
5
+ RSpec::Core::RakeTask.new
6
+
7
+ task :default => :spec
8
+ task :test => :spec
9
+
10
+ Dir.glob('lib/tasks/*.rake').each { |r| import r }
@@ -0,0 +1,14 @@
1
+ require "yaml_strings"
2
+ namespace :yaml_strings do
3
+ desc "Converts a yaml file to a strings format"
4
+ task :yaml_to_strings do
5
+ fail "YAML_FILE must be set" unless file = ENV['YAML_FILE']
6
+ fail "YAML_FILE must be set to a file" unless File.exist?(file)
7
+
8
+ yaml_hash = YAML.load(File.open(ENV['YAML_FILE']))
9
+
10
+ fail "YAML_FILE is empty" unless yaml_hash
11
+
12
+ puts YamlToStringsEncoder.new(yaml_hash).to_s
13
+ end
14
+ end
@@ -0,0 +1,18 @@
1
+ require "yaml_strings/version"
2
+ require "yaml_strings/yaml_to_strings_encoder"
3
+ require "yaml_strings/strings_to_yaml_encoder"
4
+ require "yaml_strings/load_rake_task"
5
+
6
+ module YamlStrings
7
+ class << self
8
+ def yaml_to_strings(yaml_file)
9
+ yaml_hash = YAML.load(File.open(yaml_file))
10
+ YamlToStringsEncoder.new(yaml_hash).to_s
11
+ end
12
+
13
+ def strings_to_yaml(string_file)
14
+ strings_array = File.readlines(string_file)
15
+ StringsToYamlEncoder.new(strings_array).to_s
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,9 @@
1
+ # This class ensures that all rake tasks are loaded in a Rails 3 app
2
+ if defined?(Rails)
3
+ class LoadRakeTask < Rails::Railtie
4
+ railtie_name :yaml_strings
5
+ rake_tasks do
6
+ Dir[File.join(File.dirname(__FILE__), 'tasks/*.rake')].each { |f| load f }
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,82 @@
1
+ class InvalidKeyError < StandardError; end
2
+ class InvalidValueError < StandardError; end
3
+ class InvalidTerminatorError < StandardError; end
4
+
5
+ class StringsToYamlEncoder
6
+ attr_accessor :strings_array
7
+ def initialize(strings_array = [])
8
+ @strings_array = strings_array
9
+ end
10
+
11
+ def to_s
12
+ parse_strings_array(@strings_array)
13
+ end
14
+
15
+ # Returns a hash when given
16
+ def parse_strings_array(array)
17
+ raise ArgumentError.new("Invalid strings format: missing '{\\n'") unless /{/.match(array.shift)
18
+ raise ArgumentError.new("Invalid strings format: missing '}'") unless /}/.match(array.pop)
19
+
20
+ array.inject({}) do |hash,line|
21
+ key_string, value = parse_strings_key_value(line)
22
+
23
+ key_string = remove_quotes_from_key_string(key_string)
24
+ keys = key_string.split('.')
25
+
26
+ hash.merge!(nested_hash(keys + [value]))
27
+ end
28
+ end
29
+
30
+ # %{ a b c d } =>
31
+ #
32
+ # { a => { b => { c => d } } }
33
+ #
34
+ def nested_hash(keys)
35
+ first = keys.shift
36
+ return first if keys.empty? # base case
37
+
38
+ hash = Hash.new
39
+ hash[first] = nested_hash(keys)
40
+ hash
41
+ end
42
+
43
+ # Returns true if the value is a valid string NSString
44
+ #
45
+ # See http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html#//apple_ref/doc/uid/20001012-BBCBDBJE
46
+ # for more info
47
+ def valid_string?(value)
48
+ (value =~ /\s*"[^"]*"\s*/ ||
49
+ value.strip =~ /\A\S+\Z/) &&
50
+ value.strip != ';' # handles case where no text in the value
51
+ end
52
+
53
+ # Returns true if the last character of the string, ignoring spaces, is a
54
+ # semi-colon.
55
+ def valid_terminator?(value)
56
+ return false if value.nil? || value == ""
57
+
58
+ value.gsub(' ', '')[-1] == ";"
59
+ end
60
+
61
+ def remove_quotes_from_key_string(key_string)
62
+ key_string = key_string.strip[1..-1] if key_string.strip[0] == '"'
63
+ key_string = key_string.strip[0..-2] if key_string.strip[-1] == '"'
64
+ key_string
65
+ end
66
+
67
+ # Validates the format
68
+ def parse_strings_key_value(line)
69
+ key_string, value = line.split('=')
70
+
71
+ key_string.strip!
72
+ value.strip!
73
+
74
+ raise InvalidValueError.new("Invalid strings format: Missing value for line after '=': '#{line}'") unless valid_string?(value)
75
+ raise InvalidKeyError.new("Invalid strings format: Missing key for line before '=': '#{line}'") unless valid_string?(key_string)
76
+ raise InvalidTerminatorError.new("Invalid strings format: Missing terminator ';' for line: '#{line}'") unless valid_terminator?(value)
77
+
78
+ value = value[0..-2] # Removes the ; from the value
79
+
80
+ return key_string, value
81
+ end
82
+ end
@@ -0,0 +1,3 @@
1
+ module YamlStrings
2
+ VERSION = "0.0.2"
3
+ end
@@ -0,0 +1,36 @@
1
+ class YamlToStringsEncoder
2
+ attr_accessor :yaml_hash
3
+ def initialize(yaml_hash = {})
4
+ @yaml_hash = yaml_hash
5
+ end
6
+
7
+ # Returns an array of dict properties as strings
8
+ #
9
+ # hsh - a hash to convert into the string representation
10
+ # prev_keys - a string representing the previous keys of enclosing hashes
11
+ #
12
+ # Ex: { a: :b } # => "a" = "b";
13
+ # Ex: { a: { b: :c } } # => "a.b" = "c";
14
+ def convert_hash_to_dict_property(hsh, prev_keys = nil)
15
+ result = []
16
+ hsh.each_pair {|k,v|
17
+ if v.is_a?(Hash)
18
+ new_prev_keys = "#{[prev_keys, k].compact.join('.')}"
19
+ result += convert_hash_to_dict_property(v, new_prev_keys)
20
+ else
21
+ result += ["\"#{[prev_keys, k].compact.join('.')}\" = \"#{v}\" ;"]
22
+ end
23
+ }
24
+ result
25
+ end
26
+
27
+ # Returns a string representing an old ASCII style property list
28
+ def to_property_dict_string(array_of_dict_propertes)
29
+ (["{"] + array_of_dict_propertes + ["}", nil]).join("\n")
30
+ end
31
+
32
+ def to_s
33
+ array = convert_hash_to_dict_property(yaml_hash)
34
+ to_property_dict_string(array)
35
+ end
36
+ end
@@ -0,0 +1,123 @@
1
+ require "spec_helper"
2
+
3
+ describe StringsToYamlEncoder do
4
+ it "should exist" do
5
+ lambda { subject.should be_a(StringsToYamlEncoder) }.should_not raise_error(Exception)
6
+ end
7
+
8
+ describe "#to_s" do
9
+ it "should work" do
10
+ subject.parse_strings_array(
11
+ ["{\n", "en.app_name = awesome;", "}"]
12
+ ).should eql({ "en" => { "app_name" => "awesome" } })
13
+ end
14
+ end
15
+
16
+ describe "parse_strings_array" do
17
+ it "should raise an error if missing '{'" do
18
+ lambda { subject.parse_strings_array(["}"]) }.should raise_error(ArgumentError)
19
+ end
20
+
21
+ it "should raise an error if missing '}'" do
22
+ lambda { subject.parse_strings_array(["{\n"]) }.should raise_error(ArgumentError)
23
+ end
24
+
25
+ it "should work" do
26
+ subject.parse_strings_array(
27
+ ["{\n", "en.app_name = awesome;", "}"]
28
+ ).should eql({ "en" => { "app_name" => "awesome" } })
29
+ end
30
+ end
31
+
32
+ describe "valid_string?" do
33
+ it "returns true for a quoted string" do
34
+ subject.valid_string?("\" \"").should be_true
35
+ end
36
+
37
+ it "returns true for another quoted string" do
38
+ subject.valid_string?("\"Something good here\"").should be_true
39
+ end
40
+
41
+ it "returns true for non-whitespace string" do
42
+ subject.valid_string?("something_good_here").should be_true
43
+ end
44
+
45
+ it "returns true for non-whitespace string with a terminator" do
46
+ subject.valid_string?("something_good_here;").should be_true
47
+ end
48
+
49
+ it "returns false for non-quoted space" do
50
+ subject.valid_string?(" ").should be_false
51
+ end
52
+
53
+ it "returns false for non-quoted string" do
54
+ subject.valid_string?("something good here").should be_false
55
+ end
56
+ end
57
+
58
+ describe "valid_terminator?" do
59
+ it "returns true if last character is a ;" do
60
+ subject.valid_terminator?(";").should be_true
61
+ end
62
+
63
+ it "returns true if last character is a ; ignoring spaces" do
64
+ subject.valid_terminator?(" ; ").should be_true
65
+ end
66
+
67
+ it "returns false if last character is not a ; ignoring spaces" do
68
+ subject.valid_terminator?(" ").should be_false
69
+ end
70
+
71
+ it "returns false if last character is not a ;" do
72
+ subject.valid_terminator?(";a").should be_false
73
+ end
74
+ end
75
+
76
+ describe "parse_strings_key_value" do
77
+ it "should raise an error if there is no value for a line" do
78
+ lambda { subject.parse_strings_key_value("\"a.b\" = ;") }.should raise_error(InvalidValueError)
79
+ end
80
+
81
+ it "should raise an error if there is value for a line" do
82
+ lambda { subject.parse_strings_key_value("\"a.b\" = asdf asdf;") }.should raise_error(InvalidValueError)
83
+ end
84
+
85
+ it "should raise an error if there is no key for a line" do
86
+ lambda { subject.parse_strings_key_value(" = c;") }.should raise_error(InvalidKeyError)
87
+ end
88
+
89
+ it "should raise an error if there is no terminator" do
90
+ lambda { subject.parse_strings_key_value("a.b = c") }.should raise_error(InvalidTerminatorError)
91
+ end
92
+
93
+ it "should work fine" do
94
+ key_string, value = subject.parse_strings_key_value("a.b = c;")
95
+ key_string.should eql("a.b")
96
+ value.should eql("c")
97
+ end
98
+ end
99
+
100
+ describe "remove_quotes_from_key_string" do
101
+ it "should remove \" from key_string" do
102
+ subject.remove_quotes_from_key_string('"a.b"').should eql("a.b")
103
+ end
104
+
105
+ it "should do nothing to the string" do
106
+ subject.remove_quotes_from_key_string('a.b').should eql("a.b")
107
+ end
108
+ end
109
+
110
+ describe "#nested_hash" do
111
+ it "handles one element arrays" do
112
+ subject.nested_hash([:a]).should eql(:a)
113
+ end
114
+
115
+ it "handles two element arrays" do
116
+ subject.nested_hash([:a, :b]).should eql({a: :b})
117
+ end
118
+
119
+ it "handles three element arrays" do
120
+ subject.nested_hash([:a, :b, :c]).should eql({a: { b: :c }})
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,35 @@
1
+ require "spec_helper"
2
+
3
+ describe YamlStrings, fakefs: true do
4
+ it "should create a properly formatted, new strings file" do
5
+ yaml_file = "sample.yml"
6
+ File.open(yaml_file, "w") do |f|
7
+ f.puts("a: ")
8
+ f.puts(" b: 'c'")
9
+ end
10
+
11
+ subject.yaml_to_strings(yaml_file).should eql(
12
+ <<STRINGS
13
+ {
14
+ "a.b" = "c" ;
15
+ }
16
+ STRINGS
17
+ )
18
+ end
19
+
20
+ it "should convert a strings file to a yaml representation" do
21
+ strings_file = "sample.strings"
22
+ File.open(strings_file, "w") do |f|
23
+ f.puts("{")
24
+ f.puts("a.b = 'c';")
25
+ f.puts("}")
26
+ end
27
+
28
+ subject.strings_to_yaml(strings_file).should eql(
29
+ <<YAML
30
+ a:
31
+ b: 'c'
32
+ YAML
33
+ )
34
+ end
35
+ end
@@ -0,0 +1,50 @@
1
+ require "spec_helper"
2
+
3
+ describe YamlToStringsEncoder do
4
+ describe "convert_hash_to_dict_property" do
5
+ it "converts a simple hash" do
6
+ result = subject.convert_hash_to_dict_property({ a: :b })
7
+ result.first.should eql('"a" = "b" ;')
8
+ end
9
+
10
+ it "converts a nested hash" do
11
+ result = subject.convert_hash_to_dict_property({ a: { b: :c } })
12
+ result.first.should eql('"a.b" = "c" ;')
13
+ end
14
+ end
15
+
16
+ describe "to_property_dict_string" do
17
+ it "should handle an empty array" do
18
+ subject.to_property_dict_string([]).should eql(
19
+ <<STRINGS
20
+ {
21
+ }
22
+ STRINGS
23
+ )
24
+ end
25
+
26
+ it "should properly format a dict_property" do
27
+ dict_property_string = '"a.b" = "c"; '
28
+ subject.to_property_dict_string([dict_property_string]).should eql(
29
+ <<STRINGS
30
+ {
31
+ #{dict_property_string}
32
+ }
33
+ STRINGS
34
+ )
35
+ end
36
+ end
37
+
38
+ describe "to_s" do
39
+ it "should create a properly formatted 'strings' string" do
40
+ subject.yaml_hash = { a: { b: :c } }
41
+ subject.to_s.should eql(
42
+ <<STRINGS
43
+ {
44
+ "a.b" = "c" ;
45
+ }
46
+ STRINGS
47
+ )
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,8 @@
1
+ require 'yaml_strings'
2
+ require 'mocha'
3
+ require 'fakefs/spec_helpers'
4
+
5
+ RSpec.configure do |c|
6
+ c.mock_with :mocha
7
+ c.include FakeFS::SpecHelpers, fakefs: true
8
+ end
@@ -0,0 +1,21 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/yaml_strings/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Jonathan R. Wallace"]
6
+ gem.email = ["jonathan.wallace@gmail.com"]
7
+ gem.description = %q{Convert YAML files to .string format and vice versa.}
8
+ gem.summary = %q{Converts a YAML file, specifically the ones typically used for locale and translations in Rails, to an old style Apple ASCII Property List, http://bit.ly/old_style_ascii_property_list}
9
+ gem.homepage = ""
10
+
11
+ gem.files = `git ls-files`.split($\)
12
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
13
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
14
+ gem.name = "yaml_strings"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = YamlStrings::VERSION
17
+
18
+ gem.add_development_dependency 'fakefs'
19
+ gem.add_development_dependency 'rake'
20
+ gem.add_development_dependency 'rspec'
21
+ end
metadata ADDED
@@ -0,0 +1,99 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yaml_strings
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.2
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Jonathan R. Wallace
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-03-29 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: fakefs
16
+ requirement: &70359630849240 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: *70359630849240
25
+ - !ruby/object:Gem::Dependency
26
+ name: rake
27
+ requirement: &70359630848140 !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ! '>='
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: *70359630848140
36
+ - !ruby/object:Gem::Dependency
37
+ name: rspec
38
+ requirement: &70359630847180 !ruby/object:Gem::Requirement
39
+ none: false
40
+ requirements:
41
+ - - ! '>='
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ type: :development
45
+ prerelease: false
46
+ version_requirements: *70359630847180
47
+ description: Convert YAML files to .string format and vice versa.
48
+ email:
49
+ - jonathan.wallace@gmail.com
50
+ executables: []
51
+ extensions: []
52
+ extra_rdoc_files: []
53
+ files:
54
+ - .gitignore
55
+ - Gemfile
56
+ - LICENSE
57
+ - README.md
58
+ - Rakefile
59
+ - lib/tasks/yaml_strings.rake
60
+ - lib/yaml_strings.rb
61
+ - lib/yaml_strings/load_rake_task.rb
62
+ - lib/yaml_strings/strings_to_yaml_encoder.rb
63
+ - lib/yaml_strings/version.rb
64
+ - lib/yaml_strings/yaml_to_strings_encoder.rb
65
+ - spec/lib/strings_to_yaml_encoder_spec.rb
66
+ - spec/lib/yaml_strings_spec.rb
67
+ - spec/lib/yaml_to_strings_encoder_spec.rb
68
+ - spec/spec_helper.rb
69
+ - yaml_strings.gemspec
70
+ homepage: ''
71
+ licenses: []
72
+ post_install_message:
73
+ rdoc_options: []
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ none: false
78
+ requirements:
79
+ - - ! '>='
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ none: false
84
+ requirements:
85
+ - - ! '>='
86
+ - !ruby/object:Gem::Version
87
+ version: '0'
88
+ requirements: []
89
+ rubyforge_project:
90
+ rubygems_version: 1.8.17
91
+ signing_key:
92
+ specification_version: 3
93
+ summary: Converts a YAML file, specifically the ones typically used for locale and
94
+ translations in Rails, to an old style Apple ASCII Property List, http://bit.ly/old_style_ascii_property_list
95
+ test_files:
96
+ - spec/lib/strings_to_yaml_encoder_spec.rb
97
+ - spec/lib/yaml_strings_spec.rb
98
+ - spec/lib/yaml_to_strings_encoder_spec.rb
99
+ - spec/spec_helper.rb