lib/jekyll-twitter-plugin.rb in jekyll-twitter-plugin-1.1.1 vs lib/jekyll-twitter-plugin.rb in jekyll-twitter-plugin-1.2.0

- old
+ new

@@ -2,10 +2,11 @@ ## # A Liquid tag plugin for Jekyll that renders Tweets from Twitter API. # https://github.com/rob-murray/jekyll-twitter-plugin # + module TwitterJekyll class FileCache def initialize(path) @cache_folder = File.expand_path path FileUtils.mkdir_p @cache_folder @@ -102,11 +103,11 @@ end private def key - @status_url + '%s-%s' % [@status_url, @params.to_s] end end class UnknownTypeClient include TwitterJekyll::Cacheable @@ -121,15 +122,15 @@ super @cache = FileCache.new('./.tweet-cache') args = params.split(/\s+/).map(&:strip) @api_type = args.shift @params = args - - create_twitter_rest_client end - def render(_context) + def render(context) + secrets = extract_twitter_secrets_from_context(context) || extract_twitter_secrets_from_env + create_twitter_rest_client(secrets) api_client = create_api_client(@api_type, @params) response = cached_response(api_client) || live_response(api_client) html_output_for(response) end @@ -165,16 +166,31 @@ else UnknownTypeClient.new end end - def create_twitter_rest_client + def create_twitter_rest_client(secrets) @twitter_client = Twitter::REST::Client.new do |config| - config.consumer_key = ENV.fetch('TWITTER_CONSUMER_KEY') - config.consumer_secret = ENV.fetch('TWITTER_CONSUMER_SECRET') - config.access_token = ENV.fetch('TWITTER_ACCESS_TOKEN') - config.access_token_secret = ENV.fetch('TWITTER_ACCESS_TOKEN_SECRET') + config.consumer_key = secrets.consumer_key + config.consumer_secret = secrets.consumer_secret + config.access_token = secrets.access_token + config.access_token_secret = secrets.access_token_secret end + end + + TwitterSecrets = Struct.new(:consumer_key, :consumer_secret, :access_token, :access_token_secret) + + def extract_twitter_secrets_from_context(context) + TwitterSecrets.new(context.registers[:site].config['twitter']['consumer_key'], context.registers[:site].config['twitter']['consumer_secret'], context.registers[:site].config['twitter']['access_token'], context.registers[:site].config['twitter']['access_token_secret']) if context_has_twitter_secrets?(context) + end + + def context_has_twitter_secrets?(context) + twitter_secrets = context.registers[:site].config['twitter'] || {} + ['consumer_key', 'consumer_secret', 'access_token', 'access_token_secret'].all? {|s| twitter_secrets.key?(s)} + end + + def extract_twitter_secrets_from_env + TwitterSecrets.new(ENV.fetch('TWITTER_CONSUMER_KEY'), ENV.fetch('TWITTER_CONSUMER_SECRET'), ENV.fetch('TWITTER_ACCESS_TOKEN'), ENV.fetch('TWITTER_ACCESS_TOKEN_SECRET')) end end class TwitterTagNoCache < TwitterTag def initialize(_tag_name, _text, _token)