Module: RailsConsolePro::FormatExporter
- Extended by:
- FormatExporter
- Included in:
- FormatExporter
- Defined in:
- lib/rails_console_pro/format_exporter.rb
Overview
Format exporter for converting data to JSON, YAML, and HTML
Instance Method Summary collapse
-
#export_to_file(data, file_path, format: nil) ⇒ Object
Export to file.
-
#to_html(data, title: nil, style: :default) ⇒ Object
Export to HTML format.
-
#to_json(data, pretty: true, options: {}) ⇒ Object
Export to JSON format Similar to awesome_print philosophy: convert objects to JSON-serializable structures Supports both pretty-printed and compact formats.
-
#to_yaml(data) ⇒ Object
Export to YAML format.
Instance Method Details
#export_to_file(data, file_path, format: nil) ⇒ Object
Export to file
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/rails_console_pro/format_exporter.rb', line 44 def export_to_file(data, file_path, format: nil) return nil if data.nil? format ||= infer_format_from_path(file_path) content = case format.to_s.downcase when 'json' to_json(data) when 'yaml', 'yml' to_yaml(data) when 'html', 'htm' to_html(data, title: infer_title(data)) else raise ArgumentError, "Unsupported format: #{format}. Supported: json, yaml, html" end File.write(file_path, content) file_path rescue ArgumentError, Errno::ENOENT, Errno::EACCES, Errno::ENOSPC => e # Handle file system errors gracefully nil rescue => e # Handle any other errors nil end |
#to_html(data, title: nil, style: :default) ⇒ Object
Export to HTML format
38 39 40 41 |
# File 'lib/rails_console_pro/format_exporter.rb', line 38 def to_html(data, title: nil, style: :default) html_data = serialize_data(data) generate_html(html_data, title: title || infer_title(data), style: style) end |
#to_json(data, pretty: true, options: {}) ⇒ Object
Export to JSON format Similar to awesome_print philosophy: convert objects to JSON-serializable structures Supports both pretty-printed and compact formats
14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/rails_console_pro/format_exporter.rb', line 14 def to_json(data, pretty: true, options: {}) json_data = serialize_data(data) # Apply awesome_print-style options if provided if pretty # Ruby's JSON.pretty_generate uses 2-space indentation by default JSON.pretty_generate(json_data) else JSON.generate(json_data) end rescue JSON::GeneratorError => e # Fallback for complex objects that can't be serialized { error: "Could not serialize to JSON", message: e., type: data.class.name }.to_json end |
#to_yaml(data) ⇒ Object
Export to YAML format
30 31 32 33 34 35 |
# File 'lib/rails_console_pro/format_exporter.rb', line 30 def to_yaml(data) yaml_data = serialize_data(data) # Convert symbols to strings for YAML.safe_load compatibility yaml_data = convert_symbols_to_strings(yaml_data) yaml_data.to_yaml end |