Class: HatenablogPublisher::Io
- Inherits:
-
Object
- Object
- HatenablogPublisher::Io
- Defined in:
- lib/hatenablog_publisher/io.rb
Instance Method Summary collapse
- #data_file ⇒ Object
- #data_file? ⇒ Boolean
-
#initialize(options) ⇒ Io
constructor
A new instance of Io.
- #read ⇒ Object
- #read_from_datafile(filename) ⇒ Object
- #read_from_file(filename) ⇒ Object
- #write(metadata, text) ⇒ Object
- #write_data_file(metadata) ⇒ Object
- #write_file(metadata, text) ⇒ Object
- #yaml_loader ⇒ Object
Constructor Details
#initialize(options) ⇒ Io
Returns a new instance of Io.
3 4 5 |
# File 'lib/hatenablog_publisher/io.rb', line 3 def initialize() @options = end |
Instance Method Details
#data_file ⇒ Object
11 12 13 |
# File 'lib/hatenablog_publisher/io.rb', line 11 def data_file @options.data_file end |
#data_file? ⇒ Boolean
7 8 9 |
# File 'lib/hatenablog_publisher/io.rb', line 7 def data_file? data_file.present? end |
#read ⇒ Object
45 46 47 48 49 50 51 52 53 |
# File 'lib/hatenablog_publisher/io.rb', line 45 def read filename = @options.filename if data_file? read_from_datafile(filename) else read_from_file(filename) end end |
#read_from_datafile(filename) ⇒ Object
55 56 57 58 59 60 |
# File 'lib/hatenablog_publisher/io.rb', line 55 def read_from_datafile(filename) json = JSON.parse(File.read(data_file)) target = json.find { |l| l['filepath'] == filename } [target.deep_symbolize_keys, File.read(filename)] end |
#read_from_file(filename) ⇒ Object
62 63 64 65 66 |
# File 'lib/hatenablog_publisher/io.rb', line 62 def read_from_file(filename) parsed = FrontMatterParser::Parser.parse_file(filename, loader: yaml_loader) [parsed.front_matter.deep_symbolize_keys, parsed.content] end |
#write(metadata, text) ⇒ Object
19 20 21 22 23 24 25 |
# File 'lib/hatenablog_publisher/io.rb', line 19 def write(, text) if data_file? write_data_file() else write_file(, text) end end |
#write_data_file(metadata) ⇒ Object
27 28 29 30 31 32 33 34 35 |
# File 'lib/hatenablog_publisher/io.rb', line 27 def write_data_file() data = JSON.parse(File.read(@options.data_file)) data.each do |l| next unless l['filepath'] == @options.filename l.deep_symbolize_keys!.merge!() end File.write(data_file, JSON.pretty_generate(data, indent: ' ', space_before: ' ')) end |
#write_file(metadata, text) ⇒ Object
37 38 39 40 41 42 43 |
# File 'lib/hatenablog_publisher/io.rb', line 37 def write_file(, text) filename = @options.filename parsed = FrontMatterParser::Parser.parse_file(filename, loader: yaml_loader) front_matter = parsed.front_matter.deep_symbolize_keys.merge() body = YAML.dump(front_matter.deep_stringify_keys) + "\n---\n\n" + text File.write(filename, body) end |
#yaml_loader ⇒ Object
15 16 17 |
# File 'lib/hatenablog_publisher/io.rb', line 15 def yaml_loader FrontMatterParser::Loader::Yaml.new(allowlist_classes: [Time]) end |