Home > other >  Can I include module from another file using if else condition
Can I include module from another file using if else condition

Time:02-01

Currently in my application I have one helper.rb (Helper module is defined in this file) which is included in my controller.rb file like this:

class Controller
  before_action :authenticate_user!
  include Helper

Problem is that I need to define one more module e.g. Helper2 and I don't know how to include them using if condition and I don't know if even this solution is possible.

example what I want to do:

class Controller
  before_action :authenticate_user!
  if variable = 1
    include Helper
  else
    include Helper2
  end

Thx for answers!

CodePudding user response:

YAGNI.

There are better ways.

The easist way to make the behavior customizable is to just have a set of methods that can be overridden by classes that consume the module:

module Greeter
  def initialize(name)
    @name = name
  end

  def salution
    "Hello"
  end

  def hello
    "#{salution}!, my name is #{@name}"
  end
end

class Person
  include Greeter
end

puts Person.new('Bob').hello # Hello!, my name is Bob

class Dog
  include Greeter
  def salution
    "Woof"
  end
end

puts Dog.new('Laika').hello # Woof!, my name is Laika

For more complex tasks there is the "macro method" pattern you'll see all over in Ruby:

module Configurable
  def self.included(base)
    base.extend(ClassMethods)
    base.class_eval do
      @options ||= {}
    end
  end

  module ClassMethods
    def configure(**kwargs)
      @options.merge!(kwargs) 
    end

    def options
      @options 
    end
  end
end

class Foo 
  include Configurable
  configure(bar: :baz)
end

puts Foo.options.inspect
# {:bar=>:baz}

This is simply a class method that defines class variables / class instance variables, defines methods or whatever you need to be done. For example these very simplefied API clients:

class Client
  include HTTParty
  format :json
  def answers
    self.class.get('/answers')
  end
end

class StackoverflowClient < Client
  base_uri 'https://stackoverflow.com'
end

class SoftwareEngineeringClient < Client
  base_uri 'https://softwareengineering.stackexchange.com'
end
  •  Tags:  
  • Related