From ceaed87dadc08f97892e1f3ba8d0bcb8cdc9437c Mon Sep 17 00:00:00 2001 From: yoshihara Date: Tue, 21 Apr 2015 13:06:41 +0900 Subject: [PATCH] Extract JSON generating for preview to each RegexpPreview class --- app/controllers/api_controller.rb | 13 +------------ lib/regexp_preview/multi_line.rb | 14 ++++++++++++++ lib/regexp_preview/single_line.rb | 19 ++++++++++++++++++- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/app/controllers/api_controller.rb b/app/controllers/api_controller.rb index 5db3e36..c162390 100644 --- a/app/controllers/api_controller.rb +++ b/app/controllers/api_controller.rb @@ -20,19 +20,8 @@ class ApiController < ApplicationController def regexp_preview preview = RegexpPreview.processor(params[:format]).new(params[:file], params[:format], params) - matches = preview.matches - render json: { - params: { - setting: { - # NOTE: regexp and timeformat are used when format == 'apache' || 'nginx' || etc. - # TODO: prepare rendered JSON by prcessor(RegexpPreview::{Signle,Multi}Line - regexp: preview.try(:regexp).try(:source), - time_format: preview.try(:time_format), - } - }, - matches: matches.compact, - } + render json: preview.matches_json end def grok_to_regexp diff --git a/lib/regexp_preview/multi_line.rb b/lib/regexp_preview/multi_line.rb index 06bc987..01fb1c8 100644 --- a/lib/regexp_preview/multi_line.rb +++ b/lib/regexp_preview/multi_line.rb @@ -8,6 +8,20 @@ module RegexpPreview @params = params[:params] end + def matches_json + { + params: { + setting: { # for vue.js + regexp: nil, + time_format: nil, + } + }, + matches: matches.compact, + } + end + + private + def matches return [] if patterns.empty? reader = FileReverseReader.new(File.open(file)) diff --git a/lib/regexp_preview/single_line.rb b/lib/regexp_preview/single_line.rb index 3754909..7361b62 100644 --- a/lib/regexp_preview/single_line.rb +++ b/lib/regexp_preview/single_line.rb @@ -1,11 +1,13 @@ module RegexpPreview class SingleLine - attr_reader :file, :format, :params, :regexp + attr_reader :file, :format, :params, :regexp, :time_format def initialize(file, format, params = {}) @file = file @format = format + @time_format = params[:time_format] @params = params + case format when "regexp" @regexp = Regexp.new(params[:regexp]) @@ -18,6 +20,21 @@ module RegexpPreview end end + def matches_json + { + params: { + setting: { + # NOTE: regexp and time_format are used when format == 'apache' || 'nginx' || etc. + regexp: regexp.source, + time_format: time_format, + } + }, + matches: matches.compact, + } + end + + private + def matches return [] unless @regexp # such as ltsv, json, apache, etc reader = FileReverseReader.new(File.open(file))