Skip to content

Instantly share code, notes, and snippets.

@DonKoko
Created January 24, 2017 14:31
Show Gist options
  • Save DonKoko/3e4520bd871bec332604d10465898816 to your computer and use it in GitHub Desktop.
Save DonKoko/3e4520bd871bec332604d10465898816 to your computer and use it in GitHub Desktop.
CustomDomain rails
@tournament_season =
if CustomDomain.where(:domain => request.host).any?
CustomDomain.where(:domain => request.host).first.tournament_season
else
TournamentSeason.find(params[:id])
end
class CustomDomainConstraint
def self.matches?(request)
CustomDomain.where(:domain => request.host).any?
end
end
@conarro
Copy link

conarro commented Jan 27, 2017

Here's a tweaked approach using find_by:

# updating to use ||=, just in case you ever call this method twice within the same request
# ||= will memoize the result, so it won't re-execute the logic if @tournament_season is not nil
#
# also using `begin` syntax to allow for more complex logic inside the assignment
#
@tournament_season ||= begin
  custom_domain = CustomDomain.find_by(domain: request.host)  # this will be nil of none found
  if custom_domain
    custom_domain.tournament_season
  else
    TournamentSeason.find(params[:id])
  end
end

Another round of tweaks could lead you to just move the custom domain bit into a separate private method in your controller:

# your controller stuff
# you could use the private methods as before_filters
# if you want

private

def attach_custom_domain
  @custom_domain ||= CustomDomain.find_by(domain: request.host)  # this will be nil of none found
end

def attach_tournament_season
  # and now this can be a one-liner
  @tournament_season ||= @custom_domain.present? ? custom_domain.tournament_season : TournamentSeason.find(params[:id])
end

Just some ideas for you to consider. Best of luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment