aboutsummaryrefslogtreecommitdiff
path: root/lib/core_ext
diff options
context:
space:
mode:
authorelijah <elijah@riseup.net>2012-10-10 00:09:31 -0700
committerelijah <elijah@riseup.net>2012-10-10 00:09:31 -0700
commit47062a50e9bba238191838a6625b81793afa8472 (patch)
treeb4b9603f37ba79c522edcc7193cc8e360c36f442 /lib/core_ext
parent2a4dffe29da16dec1147a7f20715a1fa657368ac (diff)
downloadleap_cli-47062a50e9bba238191838a6625b81793afa8472.tar.gz
leap_cli-47062a50e9bba238191838a6625b81793afa8472.tar.bz2
hierarchical yaml output.
Diffstat (limited to 'lib/core_ext')
-rw-r--r--lib/core_ext/boolean.rb14
-rw-r--r--lib/core_ext/hash.rb74
-rw-r--r--lib/core_ext/nil.rb5
3 files changed, 93 insertions, 0 deletions
diff --git a/lib/core_ext/boolean.rb b/lib/core_ext/boolean.rb
new file mode 100644
index 0000000..9b617b2
--- /dev/null
+++ b/lib/core_ext/boolean.rb
@@ -0,0 +1,14 @@
+#
+# make is_a?(Boolean) possible.
+#
+
+module Boolean
+end
+
+class TrueClass
+ include Boolean
+end
+
+class FalseClass
+ include Boolean
+end \ No newline at end of file
diff --git a/lib/core_ext/hash.rb b/lib/core_ext/hash.rb
new file mode 100644
index 0000000..a9e5c9e
--- /dev/null
+++ b/lib/core_ext/hash.rb
@@ -0,0 +1,74 @@
+#
+#
+# We modify Hash to add a few features we need:
+#
+# * sorted output of keys to in yaml.
+# * reference values either with hsh[key] or hsh.key
+# * deep merge
+# * select fields
+#
+# Because the json parsing code we use doesn't support setting a custom class, it is easier for us to just modify Hash.
+#
+
+require 'yaml'
+
+class Hash
+
+ ##
+ ## YAML
+ ##
+
+ #
+ # make the type appear to be a normal Hash in yaml, even for subclasses.
+ #
+ def to_yaml_type
+ "!map"
+ end
+
+ #
+ # just like Hash#to_yaml, but sorted
+ #
+ def to_yaml(opts = {})
+ YAML::quick_emit(self, opts) do |out|
+ out.map(taguri, to_yaml_style) do |map|
+ keys.sort.each do |k|
+ v = self[k]
+ map.add(k, v)
+ end
+ end
+ end
+ end
+
+ ##
+ ## CONVERTING
+ ##
+
+ #
+ # convert self into a plain hash, but only include the specified keys
+ #
+ def pick(*keys)
+ keys.map(&:to_s).inject({}) do |hsh, key|
+ if has_key?(key)
+ hsh[key] = self[key]
+ end
+ hsh
+ end
+ end
+
+ #
+ # recursive merging (aka deep merge)
+ # taken from ActiveSupport::CoreExtensions::Hash::DeepMerge
+ #
+ # def deep_merge(other_hash)
+ # self.merge(other_hash) do |key, oldval, newval|
+ # oldval = oldval.to_hash if oldval.respond_to?(:to_hash)
+ # newval = newval.to_hash if newval.respond_to?(:to_hash)
+ # oldval.class.to_s == 'Hash' && newval.class.to_s == 'Hash' ? oldval.deep_merge(newval) : newval
+ # end
+ # end
+
+ # def deep_merge!(other_hash)
+ # replace(deep_merge(other_hash))
+ # end
+
+end
diff --git a/lib/core_ext/nil.rb b/lib/core_ext/nil.rb
new file mode 100644
index 0000000..05ca98f
--- /dev/null
+++ b/lib/core_ext/nil.rb
@@ -0,0 +1,5 @@
+class NilClass
+ def any?
+ false
+ end
+end \ No newline at end of file