Sinatra asset pipeline, can't make it work - css

I am using Sprockets with Sinatra, as suggested in Sinatra's page docs, but I can't make it work.
When I go to localhost:4567, the page loads correctly but with no styles. If I go to localhost:4567/assets/app.css, I get a not found error. I wonder what I am missing or what is wrong in the way I am using Sprockets?
This is my folder structure:
├── assets
│   ├── css
│   │   ├── app.css
│   │   ├── base.css
│   │   └── normalize.css
├── bin
│   └── app
├── lib
│   ├── app_assets.rb
│   └── main.rb
├── spec
│   ├── spec_helper.rb
│   └── main_spec.rb
├── views
│   └── index.erb
├── Gemfile
├── Gemfile.lock
├── Rakefile
├── .rspec
└── .ruby-version
The contents of app.css are:
//= require normalize
//= require base
The contents of app_assets.rb are:
module AppAssets
def self.environment root_path
environment = Sprockets::Environment.new root_path
environment.append_path './assets/css/'
environment
# get assets
get '/assets/*' do
env['PATH_INFO'].sub!('/assets', '')
settings.environment.call(env)
end
end
end
The contents of lib/main.rb are:
require 'sinatra'
require 'sprockets'
require 'app_assets'
class Main < Sinatra::Base
set :views, "#{settings.root}/../views"
get '/' do
erb :index
end
end
The file views/index.erb contains the line:
<link rel="stylesheet" href="assets/app.css">
And the contents of bin/app are:
#!/usr/bin/env ruby
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib')
require 'sinatra'
require 'sprockets'
require 'app_assets'
require 'main'
Main.run!
Which I run typing:
$ bin/app
Any help would be appreciated, I'm sure I made something wrong but I can't see what. Can anybody spot it?

The app_assets.rb file is the problem here. When you require this file inside another file, the methods you define inside this module are not automatically included. You need to explicitly include AppAssets wherever you need the self.environment method to exist.
The second issue here is that self.environment is not equivalent to settings.environment. If I understand correctly, what you're trying to do is define the asset routing whenever the module gets included. To achieve this one way is to use the included hook for modules. This hook gets run every time you include a module inside a context. If you use that, the code in app_assets.rb turns to:
module AppAssets
def self.included(klass)
environment = Sprockets::Environment.new klass.settings.root
# note the change to path. Since the file where this gets included
# is inside a sub-folder, we need to traverse to one level above.
environment.append_path '../assets/css/'
klass.set :environment, environment
klass.get '/assets/*' do
env['PATH_INFO'].sub!('/assets', '')
klass.settings.environment.call(env)
end
end
end
The klass argument to this hook is the class into which this module is included. In our case this is the Sinatra class you've described in main.rb. That file looks like:
class Main < Sinatra::Base
include AppAssets
# Same as what you have
end
There's a Sinatra Recipes article about using Sprockets with Sinatra: http://recipes.sinatrarb.com/p/asset_management/sprockets?#article

Related

How to generate a single python file from several proto files

I have a project with a proto files in a:
$ tree proto/
proto/
├── common
│   └── request.proto
├── file
│   ├── file.proto
│   └── file_service.proto
├── job
│   ├── job.proto
│   └── job_service.proto
├── pool
│   ├── pool.proto
│   └── pool_service.proto
└── worker
├── worker.proto
└── worker_service.proto
5 directories, 9 files
I want to generate a one single file from worker_service.proto but these file has imports from common.
Is there a option in grpc_tools.protoc to generate one single python file?
Or is there a tool to generate one proto file?
Based on the information, I guess by generate one Python file means: instead of generate one Python file for messages (*_pb2.py) and one Python file for services (*_pb2_grpc.py), you hope to concatenate both of them into one Python file. To take a look at the generated file content, here is the Helloworld example.
Combining the two output file is currently not supported by the gRPC Python ProtoBuf plugin (unlike Java/Go). You can post a feature request and add more detail about your use case: https://github.com/grpc/grpc/issues

“Controller does not exist. Reflection failed.” TYPO3 v2

I have a typo3 extension (created with extension manager) and it seems no matter what I try I always get the following error:
Class CM\Parser\Controller\ParserController does not exist. Reflection failed.
I used the explanations for this problem TYPO3 tutorial extension, controller does not exist and "Controller does not exist. Reflection failed." TYPO3. Neither of them seem to work.
My composer.json in the root directory has the following entry:
"autoload": {
"psr-4": {
"CM\\parser\\": "./packages/cm-parser/Classes"
}
}
My typo3conf/ext folder has a symlink on packages/cm-parser. My composer.json inside the extension directory (packages/cm-parser) has the entry:
"autoload": {
"psr-4": {
"CM\\parser\\": "./Classes"
}
}
Thanks in advance for any help.
My directory structure looks like this (starting in /opt/lampp/htdocs/my-new-project) which is a typo3 v9.5 installation
> .
├── packages
│   └── cm-parser
│   ├── Classes
│   ├── Configuration
│   ├── Documentation.tmpl
│   ├── Resources
│   └── Tests
├── public
│   ├── fileadmin
│   │   ├── _processed_
│   │   ├── _temp_
│   │   └── user_upload
│   ├── typo3
│   │   └── sysext
│   ├── typo3conf
│   │   ├── ext
│   │   └── l10n
│   ├── typo3temp
│   │   ├── assets
│   │   └── var
│   └── uploads
│   └── tx_extensionbuilder
├── var
...
In my typo3conf/ext directory there is a symlink called parser to packages/cm-parser (I think the composer created that for me).
So I hope this symlink works for Typo3.
The files ext_emconf.php and ext_localconf.php are also in the right place. The folder structure above only displays my folders (tree -L 3) up to the third level.
The controller class is CM\Parser\Controller\ParserController, while in your composer.json you're using CM\\parser\\ (with a lowercase p) in the PSR4 autoload. This should be CM\\Parser\\
After changing this you need to of course run composer dumpautoload to reload the autoload information.
In your root composer.json file:
➊ You do not need the PSR-4 autoload section for "CM\\parser\\".
➋ You possibly have to add the path to packages/* as a repository.
➌ You have to include the composer namespace of your extension.
In your file system:
➍ You do not need typo3conf/ext/ as a symbolic link to packages/.
Try the following changes:
In your root composer.json file, remove the PSR-4 autoload section as outlined above. Add the packages/ directory as a path under repositories. For example:
{
"repositories": [
{
"type": "composer",
"url": "https://composer.typo3.org/"
},
{
"type": "path",
"url": "packages/*"
}
],
...
}
Store your extension code in the following path: packages/parser/.
Assuming your extension key reads parser and your vendor name is CM, the composer namespace becomes cm/parser. Add this as a requirement to the composer config file. You can use the following command on the command line:
composer require cm/parser:dev-master
This assumes, that packages/parser/ is a valid Git repository and has the master branch (do not use a version in the extension's composer.json file).
If the local Git repository and version (in the example above: dev-master) can be found, composer will automatically install all dependencies as required and it will create a symbolic link:
typo3conf/ext/parser -> ../../../packages/parser/
Also double check if all PHP files show the correct PHP namespace: CM\Parser\... and your controller class name reads ParserController.
If you can share your TYPO3 extension code, upload it to GitHub (or any other place) and share the link here. This way people can review your code and possibly spot further errors.

Only enable eslint in specific files

I really like eslint for es6 projects. Previously I've used it for new projects. Now I want to add it to a legacy project.
Fixing all pre-existing lint issues in one go is too much effort. Can I configure eslint (in .eslintrc.js) to only check files where I've explicitly enabled it with /* eslint-enable */ or similar?
ESLint has no default-disabled state that can be toggled by a file comment. You might be able to use .eslintignore for this purpose, however. You can ignore everything and then gradually whitelist files as you migrate them by using ! to un-ignore individual files. For example:
.
├── .eslintignore
├── .eslintrc.js
├── package.json
├── node_modules
│   └── ...
├── src
│   ├── index.js
│   └── module
│   └── foo.js
└── yarn.lock
Then your .eslintignore could look something like this:
# Start by ignoring everything by default
src/**/*.js
# Enable linting just for some files
!src/module/foo.js
In this case, src/index.js would be ignored, but it would lint src/module/foo.js.

CSS won't load in Gulp production build

I'm using the generator-gulp-angular library. In development, everything, including my CSS, works perfectly. When I do a production build, most of the CSS isn't being loaded.
The symptom of the problem is pretty simple. After I do a gulp build, my single CSS file looks like this:
#import url(assets/css/application/dashboard.index.css);
#import url(assets/css/application/detail.alerts.css);
#import url(assets/css/application/detail.index.css);
#import url(assets/css/application/detail.map.css);
#import url(assets/css/application/detail.pod.css);
This goes on for a while. (I had to drop in a bunch of CSS files created by a separate development team.)
The same exact thing happens in development mode, but in development the imported files are found and in production they're not. (Production is Heroku, FWIW.)
The main thing I can't understand is why the heck the CSS files are found in development. This is what a tree of .tmp looks like:
.tmp
├── partials
│   └── templateCacheHtml.js
└── serve
├── 404.html
├── app
│   ├── index.css
│   ├── index.js
│   ├── vendor.css
│   └── views
│   ├── shipments
│   │   └── index.html
│   └── user-sessions
│   └── new.html
└── index.html
6 directories, 8 files
There's obviously no assets/css/... in .tmp. The only place, for example, dashboard.index.css exists is in assets/css, which lives in src/app/ as opposed to public or anything like that.
I'm pretty stumped. Any guidance would be appreciated.
I ended up changing all css to scss and that fixed the problem.

A simple example of Django and CSS

I'm new to Django, and am trying to set up a really simple Django app.
Now, I'm up to chapter 5 in the Django online book : http://www.djangobook.com/en/2.0/chapter05/
All I want to do now, before I start trying databases, is to add in some simple CS and J to the app as is.
So the question is, how do I do this? I only have one app, and I only want a main.css in a css folder, and a main.js in a js folder.
I checked out the https://docs.djangoproject.com/en/1.3/howto/static-files/#staticfiles-in-templates page, but after reading and reading, there didn't seem to be a whole lot to work with in terms of examples.
How do I import the stylesheets/css (is there a helper like CakePHP?), where do I put the CSS and JS files, and do I need to configure the static thingy?
UPDATE: the link : Render CSS in Django does not help much. Mainly in that it didn't work for me, but also I especially don't like the "if debug" part. What happens when I move to prod? Why would I have my media folder defined differently for prod and local dev anyway? Shouldn't it be relative, or even in the same spot?
If you follow django's guidelines, you can simplify your life greatly.
In your sample code, inside your application directory, create a folder called static. Inside this folder, place your css files.
Example:
$ django-admin.py startproject myproject
$ cd myproject
myproject$ python manage.py startapp myapp
myproject$ mkdir myapp/static
myproject$ cd myapp/static
myproject/myapp/static$ nano style.css
In your templates:
<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />
Make sure you add myapp to the INSTALLED_APPS list in settings.py. Now when you use the built-in development server, your style sheet will be rendered correctly.
Django searches for a static directory inside installed applications by default, and with current versions of django, static files are enabled by default.
The Django example has the path my_app/static/my_app/myimage.jpg which
is a little confusing if your app and project have the same name.
This is recommended because when you run collectstatic to gather all your static files, files with the same name will be overwritten. If you have a file called myimage.jpg in another application, it will be overwritten. Giving the application name inside the static directory will prevent this, because the exact directory structure will be replicated inside your STATIC_ROOT directory.
A simple example to illustrate the point. If you have a django project with two apps, like this:
.
├── assets
├── manage.py
├── myapp
│   ├── __init__.py
│   ├── models.py
│   ├── static
│   │   └── myapp
│   │   └── test.txt
│   ├── tests.py
│   └── views.py
├── myproj
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   └── wsgi.py
└── otherapp
├── __init__.py
├── models.py
├── static
│   └── otherapp
│   └── test.txt
├── tests.py
└── views.py
assets is your STATIC_ROOT. Now when you run collectstatic:
.
├── assets
│   ├── myapp
│   │   └── test.txt
│   └── otherapp
│   └── test.txt
├── manage.py
├── myapp
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── models.py
│   ├── static
│   │   └── myapp
│   │   └── test.txt
│   ├── tests.py
│   └── views.py
├── myproj
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   └── wsgi.py
└── otherapp
├── __init__.py
├── __init__.pyc
├── models.py
├── static
│   └── otherapp
│   └── test.txt
├── tests.py
└── views.py
You see it is creating the directories as well. In your templates you would now refer to each file with its "namespace" of the app: {{ STATIC_URL }}/myapp/test.txt
The recommended approach has changed again (from at least Django 1.5 I think).
At the top of your template put:
{% load staticfiles %}
Then, using the same directory structure (myapp/static/myapp/style.css):
<link rel="stylesheet" href="{% static 'myapp/style.css' %}" />
Source
For the examples you pointed at to work, your static files need to be in a location accessible to Django's built-in staticfiles app.
There are a couple steps to make this happen:
First, within your project directory (ie beside your manage.py file), you'll need to create a directory to hold your static files. Call it "static_files".
Next, you'll need to let Django know to look in that directory, by specifying it in the list of STATICFILES_DIRS within your settings.py file.
Something like this:
STATICFILES_DIRS = [
'/full/path/to/your/project/static_files/',
]
Within that static_files directory, you can create whatever structure you want, so that is where your css and js directories could go.
After that, you should be able to use the {{ STATIC_URL }} tag in your templates to get access to the base URL of your static files.
So, say, for example, you create project/static_files/css/base.css, you would use it in your template like so:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/base.css" />
Hope that helps!
Edit
With the default settings for STATICFILES_FINDERS, Django should automatically serve up any files from directories listed in your STATICFILES_DIRS -- see the docs for details.
If this doesn't work, some things to check:
Have you edited your STATICFILES_FINDERS setting to something other than the default?
Is django.contrib.staticfiles in your list of INSTALLED_APPS in settings.py?
Are you using Django's built-in server (python manage.py runserver)?
Do you have DEBUG = True in your settings.py? If not, you'll need to either set it to True or use the insecure option (python manage.py runserver --insecure). When going to production, check out the collectstatic command.
finally i got after many days here is how should be done
1> you need your static file in your app along with in your project
2> here is setting.py
if DEBUG:
STATIC_ROOT = "/PycharmProjects/don/admin/shopping/static/css"
STATICFILES_DIRS =(
#os.path.join(os.path.dirname(BASE_DIR),"static","static"),
os.path.join(BASE_DIR, "static"),
)
3>views.py
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'index.html'
4> template file
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
5> urls.py
from shopping.views import HomeView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', HomeView.as_view())
]
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
6> python manage.py collectstatic
have fun :)
The handling of static files has changed significantly (for the better) in Django 1.3. In particular is the flexible difference between static files (think code required CSS/JS/images) and media files (think images uploaded by users in the use of you application). The staticfiles app handles what you are asking for.
Put django.contrib.staticfiles in your settings.py INSTALLED_APPS. Then create a static directory inside your app directory - so project/app/static/. Within that static directory organize your support files as you like (css/, js/, images/, icons/, etc). staticfiles by default will look in the static/ directory for every app listed in INSTALLED_APPS. Not just your own, but all the Django apps and third-party apps. (sidenote: the Admin in Django 1.4 moves to this paradigm while in 1.3 it still uses the ADMIN_MEDIA_PREFIX).
The staticfiles app knows about all those static/ directories in all the apps but it needs to collect all that content in order to serve it. In development, when using manage.py runserver it is handled for you. Django will run your site and automatically deliver all the static content from all the static sources. (Sources, as mentioned in another answer, are set in the STATICFILES_FINDERS setting.) When not using runserver, use manage.py collectstatic to gather all the static files into the folder defined in STATIC_ROOT. Keep this directory empty. It is a collection destination. Of course your web server will need to be configured to serve this directory.
Now there is one more piece - the view. This is where the STATIC_URL comes into play. When referring to static files in your templates, the easiest way is to use {{ STATIC_URL }}. Django by default makes that variable available to any view using the RequestContext. Do something like this - <link rel="stylesheet" href="{{ STATIC_URL }}/css/main.css" />.
For more information and more ways to refer to STATIC_URL in your templates, check out this answer to a similar question.
Here's a hacky workaround for views.py when debug in settings.py is False
def my_style(request):
my_file = open('path to arbitrary css file', 'r')
response = HttpResponse(content=my_file.read())
response['Content-Type'] = 'text/css'
return response
and here's the urls.py
urlpatterns = [
path('hello', views.hello_world, name='hello_world'),
path('static/my_style/', views.my_style, name='my_style'),
]
And here's the insert for the html file
<link rel="stylesheet" type="text/css" href="static/my_style">
Though this is clearly not how Django was meant to be used, and I'm guessing this could have some security implications.

Resources