require 'pathname'
require 'rest_client'

module CapybaraScreenshotIdobata
  module DSL
    def save_screenshot_and_post_to_idobata(filename = "screenshot-#{Time.now.to_i}.png", options = {})
      raise 'missing config `CapybaraScreenshotIdobata.hook_url`' unless CapybaraScreenshotIdobata.hook_url

      options = detect_default_option(Capybara.current_driver).merge(options)

      save_screenshot filename, options

      absolute_filepath, line = caller[0].split(':')

      filepath = Pathname(absolute_filepath).relative_path_from(Pathname(Dir.pwd))

      source = CapybaraScreenshotIdobata.message_formatter.call(filepath, line, self)

      File.open(filename, 'rb') do |file|
        RestClient.post(CapybaraScreenshotIdobata.hook_url,
          {
            source: source,
            format: CapybaraScreenshotIdobata.message_format,
            image:  file
          },
          {
            'User-Agent' => "CapybaraScreenshotIdobata/v#{CapybaraScreenshotIdobata::VERSION}"
          }
        )
      end
    end

    def detect_default_option(driver)
      case driver
      when :poltergeist
        {full: true}
      else
        {}
      end
    end
  end
end

require 'pathname'
require 'rest_client'

module CapybaraScreenshotIdobata
  module DSL
    def save_screenshot_and_post_to_idobata(filename = "screenshot-#{Time.now.to_i}.png", options = {})
      raise 'missing config `CapybaraScreenshotIdobata.hook_url`' unless CapybaraScreenshotIdobata.hook_url

      options = detect_default_option(Capybara.current_driver).merge(options)

      screenshot_path = save_screenshot(filename, options)

      absolute_filepath, line = caller[0].split(':')

      filepath = Pathname(absolute_filepath).relative_path_from(Pathname(Dir.pwd))

      source = CapybaraScreenshotIdobata.message_formatter.call(filepath, line, self)

      File.open(screenshot_path, 'rb') do |file|
        RestClient.post(CapybaraScreenshotIdobata.hook_url,
          {
            source: source,
            format: CapybaraScreenshotIdobata.message_format,
            image:  file
          },
          {
            'User-Agent' => "CapybaraScreenshotIdobata/v#{CapybaraScreenshotIdobata::VERSION}"
          }
        )
      end
    end

    def detect_default_option(driver)
      case driver
      when :poltergeist
        {full: true}
      else
        {}
      end
    end
  end
end

Fix screenshot path using return value of `save_screenshot`
Fix screenshot path using return value of `save_screenshot`

Since this commit (https://github.com/jnicklas/capybara/commit/75084c59),
`Capybara::Session#save_screenshot` depends on `Capybara.save_path` when
filename is a relative path.

Before:
`Pathname(Dir.pwd).join(filename)`

After:
`Pathname(Capybara.save_path).join(filename)`

If we call `save_screenshot_and_post_to_idobata` with a relative path (or
no arguments), `File.open(filename)` is failed to find a screenshot.
