Last active
December 16, 2015 22:59
-
-
Save DavidBarry/5510975 to your computer and use it in GitHub Desktop.
A ruby script that turns an enum definition into a switch statement.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'optparse' | |
enum_string = "" | |
statements = "<#statements#>" | |
switch_expression = "<#expression#>" | |
tab_width = 4 | |
use_tabs = false; | |
OptionParser.new do |option| | |
option.on('-e', '--enum [enum]', String, 'The enum definition, whole or part.') do |in_enum| | |
enum_string = in_enum | |
end | |
option.on('-s', '--statements [statements]', String, 'A string to be inserted in each case.') do |in_statements| | |
statements = in_statements | |
end | |
option.on('-x', '--expression [expression]', String, 'The expression to switch over.') do |in_expression| | |
switch_expression = in_expression | |
end | |
option.on('-t', '--use-tabs', 'Use tabs instead of spaces.') do |in_use_tabs| | |
use_tabs = true | |
end | |
option.on('-w', '--tab-width [tabwidth]', Integer, 'The number of spaces in a tab.') do |in_tab_width| | |
tab_width = in_tab_width | |
end | |
end.parse!(ARGV) | |
tab = use_tabs ? "\t" : " " * tab_width | |
temp_enum = enum_string.split(/[\{\}]/) # Get rid of the brackets in case we're given a full definition | |
if temp_enum.count > 1 then enum_string = temp_enum[1] end # If it was a full definition the good stuff will be the second item | |
switch_statement = "switch (#{switch_expression}) {\n" | |
enum_string.split(',').each do |item| | |
item = item.split('=')[0].strip # Get rid of the assignment | |
if !item.empty? then switch_statement << "#{tab}case #{item}:\n#{tab * 2}#{statements}\n#{tab * 2}break;\n" end | |
end | |
switch_statement << "#{tab}default:\n#{tab * 2}break;\n}\n" | |
copy_command = "echo \"#{switch_statement}\" | pbcopy" | |
%x( #{copy_command} ) | |
puts 'Done!' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can pass either a full enum definition, or just the comma separated enum values you want to use.
Example 1
Full enum definition
Output
Example 2
Partial enum definition
Output
There are a few ways to customize the output:
-t
or--use-tabs
-w
or--tab-width
-v
or--switch-variable
-a
or--action