Thanks to visit codestin.com
Credit goes to github.com

Skip to content

require_server_side_file method #360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
catmando opened this issue Feb 24, 2021 · 1 comment
Closed

require_server_side_file method #360

catmando opened this issue Feb 24, 2021 · 1 comment
Labels
enhancement New feature or request

Comments

@catmando
Copy link
Contributor

this should be added very soon to edge. In the meantime you can begin using it now!

It can be very useful to structure your models and operations into common (client and server) and server only definitions.

We have been doing this by including modules defined in app/models or app/operations with a unless RUBY_ENGINE == 'opal' guard.

This is cumbersome, and also requires moving a lot of stuff around if adding hyperstack to a brownfield site.

The require_server_side_file method solves the problem nicely. Just add that declaration to the beginning of any file in a hyperstack directory, and the matching file from the app directory will be required, BUT ONLY ON THE SERVER.

The following method can be added to the beginning of your hyperstack/models/application_record.rb file:

class Object
  def require_server_side_file
    return if RUBY_ENGINE == 'opal'

    path = caller[0].split(':')[0].split(File::SEPARATOR).reverse
    hs_index = path.length.times { |i| break i if path[i] == 'hyperstack' }
    new_path = (path[0..hs_index - 1] + path[hs_index + 1..-1]).reverse
    load_path = new_path.join(File::SEPARATOR)
    require_dependency load_path
  end
end

The you can say (for example)

# app/hyperstack/models/my_big_model.rb
require_server_side_file

class MyBigModel < ApplicationRecord 
   ... definitions visible to the client AND server ...
end
# app/models/my_big_model.rb

class MyBigModel < ApplicationRecord 
  ... definitions only available on the server ...
end

How it works:

the hyperstack directory is before the app directory, so rails will find the hyperstack file first. Normally once rails finds a file that defines the constant it is looking for it quits, and so the server side file wont get loaded, unless you explicitly do a require_dependency on it.

The method above simply automtically does the require_dependency, but only when running on the server.

@catmando
Copy link
Contributor Author

Superceeded by issue #361

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant