草庐IT

android - 在 firebase 中使用数据库时按下按钮会导致无法解释的 'redirect'

coder 2023-12-29 原文

我在开发 Android 应用程序时遇到了无法解释的按钮效果问题。

这涉及三个 Activity :(您可以在 pastebin 上找到完整代码)

TripListActivity.java

//removed imports due to body limitation at 30000 chas
public class TripListActivity extends AppCompatActivity {

    @BindView(R.id.rlvTrips)
    RecyclerView rlvTrips;

    private DatabaseReference databaseReference;
    private FirebaseAuth firebaseAuth;
    private FirebaseStorage firebaseStorage;

    private List<Trip> recentTrips;
    private List<Trip> pastTrips;
    private List<StorageReference> imageRefsRecent;
    private List<StorageReference> imageRefsPast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //create instance of firebase auth
        firebaseAuth = FirebaseAuth.getInstance();

        //create instance of firebase storage
        firebaseStorage = FirebaseStorage.getInstance();

        //create instance of firebase database
        databaseReference = FirebaseDatabase.getInstance().getReference();

        recentTrips = new ArrayList<>();
        pastTrips = new ArrayList<>();
        imageRefsRecent = new ArrayList<>();
        imageRefsPast = new ArrayList<>();

        getAllTrips();
    }

    private void getAllTrips() {
        final Date currentDate = new Date();
        final long currentTime = currentDate.getTime();
        databaseReference.child("users/" + firebaseAuth.getCurrentUser().getUid() + "/").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                DataSnapshot tripsDataSnapshot = dataSnapshot.child("trips");
                for (DataSnapshot tripDataSnapshot : tripsDataSnapshot.getChildren()) {
                    Trip trip = new Trip();

                    trip.setTitle((String) tripDataSnapshot.child("title").getValue());
                    trip.setDescription((String) tripDataSnapshot.child("description").getValue());


                    DataSnapshot dateDataSnapshot = tripDataSnapshot.child("date");
                    Date date = new Date();
                    if (dateDataSnapshot.child("time").getValue() != null) {
                        date.setTime((Long) dateDataSnapshot.child("time").getValue());
                    }
                    trip.setDate(date);

                    DataSnapshot imagesDataSnapshot = tripDataSnapshot.child("images");
                    List<String> imageList = new ArrayList<>();
                    for (int i = 1; i <= imagesDataSnapshot.getChildrenCount(); i++) {
                        imageList.add(String.valueOf(imagesDataSnapshot.child("img" + i).getValue()));
                    }
                    trip.setImages(imageList);

                    DataSnapshot placesDataSnapshot = tripDataSnapshot.child("places");
                    List<Place> placeList = new ArrayList<>();
                    for (int i = 0; i < placesDataSnapshot.getChildrenCount(); i++) {
                        Place place = new Place();
                        place.setLat((String) placesDataSnapshot.child(String.valueOf(i)).child("lat").getValue());
                        place.setLng((String) placesDataSnapshot.child(String.valueOf(i)).child("lng").getValue());
                        placeList.add(place);
                    }
                    trip.setPlaces(placeList);

                    Log.d(TripListActivity.class.getSimpleName(), "Trip date = " + date.getTime() + "   current time = " + currentTime);
                    if (currentTime - date.getTime() <= SEVEN_DAYS_IN_MILISECONDS) {
                        recentTrips.add(trip);
                        //get first image form each trip
                        imageRefsRecent.add(firebaseStorage.getReferenceFromUrl(imageList.get(0)));
                    } else {
                        pastTrips.add(trip);
                        //get first image form each trip
                        imageRefsPast.add(firebaseStorage.getReferenceFromUrl(imageList.get(0)));
                    }

                }

                provideRecentTripsUI();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d("-----Error-----", databaseError.getMessage());
            }
        });
    }

    private void populateTripList(final List<Trip> tripList, List<StorageReference> imageRefs) {
        TripAdapter tripAdapter = new TripAdapter(tripList, imageRefs, getApplicationContext());

        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 2);
        //set on item click listener
        tripAdapter.setItemClickListener(new TripAdapter.ItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE).edit();
                sharedPreferencesEditor.putString(TRIP_CLICKED_TITLE, tripList.get(position).getTitle());
                sharedPreferencesEditor.putString(TRIP_CLICKED_DESCRIPTION, tripList.get(position).getDescription());
                sharedPreferencesEditor.apply();

                Intent tripDetailIntent = new Intent(TripListActivity.this, TripDetailActivity.class);
                tripDetailIntent.putExtra("tripClicked", tripList.get(position));
                tripDetailIntent.putExtra("tripId", position + 1);
                tripDetailIntent.putExtra("userUID", firebaseAuth.getCurrentUser().getUid());
                startActivity(tripDetailIntent);
            }
        });
        rlvTrips.setLayoutManager(layoutManager);
        rlvTrips.setItemAnimator(new DefaultItemAnimator());
        rlvTrips.setAdapter(tripAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case R.id.recentTrips:
                provideRecentTripsUI();
                return true;
            case R.id.pastTrips:
                providePastTripsUI();
                return true;
            case R.id.addTrip:
                Intent intent = new Intent(this, TripAdderActivity.class);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void provideRecentTripsUI() {
        if (recentTrips.size() != 0) {
            setContentView(R.layout.activity_trip_list);
            ButterKnife.bind(TripListActivity.this);
            populateTripList(recentTrips, imageRefsRecent);
        } else {
            setContentView(R.layout.no_recent_trips_layout);
        }
    }

    public void allTripsMode(View view) {
        providePastTripsUI();
    }

    private void providePastTripsUI() {
        setContentView(R.layout.activity_trip_list);
        ButterKnife.bind(TripListActivity.this);
        populateTripList(pastTrips, imageRefsPast);
        if (pastTrips.size() == 0) {
            ToastUtil.showToast("No past trips!", this);
        }
    }

}

TripAdderActivity.java

//removed imports due to body limitation at 30000 chas
public class TripAdderActivity extends AppCompatActivity {


    @BindView(R.id.etTitle)
    EditText etTitle;
    @BindView(R.id.etDescription)
    EditText etDescription;
    @BindView(R.id.lvMedia)
    ListView lvMedia;

    private FirebaseAuth firebaseAuth;
    private FirebaseStorage firebaseStorage;
    private DatabaseReference databaseReference;

    private ArrayList<Uri> imageURIs;
    private Trip trip;
    private Date date;
    private long tripId;

    public static final int PICK_IMAGE_REQUEST = 1;
    private String imageEncoded;
    private List<String> imagesEncodedList;

    static boolean placesAdded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trip_adder);

        //bind views
        ButterKnife.bind(this);

        trip = new Trip();
        imageURIs = new ArrayList<>();

        //get current time
        date = Calendar.getInstance().getTime();

        //create instance of firebase auth
        firebaseAuth = FirebaseAuth.getInstance();

        //create instance of firebase storage
        firebaseStorage = FirebaseStorage.getInstance();

        //get database reference
        databaseReference = FirebaseDatabase.getInstance().getReference();

        //read number of trips from the database
        databaseReference.child("users/" + firebaseAuth.getCurrentUser().getUid() + "/").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                tripId = (long) dataSnapshot.child("tripNumber").getValue();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TripListActivity.class.getSimpleName(), "Failed to read trip.");
            }
        });
    }

    /**
     * @param view This method sends the user to a MapActivity.
     */
    public void addPlace(View view) {
        Intent intent = new Intent(this, MapsAdderActivity.class);
        intent.putExtra("tripId", tripId);
        startActivity(intent);
    }

    /**
     * @param view This method uses an intent to allow the user to pick images that he wants to add to the Trip object
     *             and stores the images in firebase storage.
     */
    public void addMedia(View view) {
        (new AddImagesTask() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();

            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
            }
        }).execute();


        Intent intent = new Intent();
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            // When an Image is picked
            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                imagesEncodedList = new ArrayList<String>();
                if (data.getData() != null) {

                    Uri mImageUri = data.getData();

                    // Get the cursor
                    Cursor cursor = getContentResolver().query(mImageUri,
                            filePathColumn, null, null, null);
                    // Move to first row
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    imageEncoded = cursor.getString(columnIndex);
                    cursor.close();

                } else {
                    if (data.getClipData() != null) {
                        ClipData mClipData = data.getClipData();
                        ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                        for (int i = 0; i < mClipData.getItemCount(); i++) {

                            ClipData.Item item = mClipData.getItemAt(i);
                            Uri uri = item.getUri();
                            mArrayUri.add(uri);
                            // Get the cursor
                            Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                            // Move to first row
                            cursor.moveToFirst();

                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                            imageEncoded = cursor.getString(columnIndex);
                            imagesEncodedList.add(imageEncoded);
                            cursor.close();

                        }
                        Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());

                        imageURIs = mArrayUri;

                        uploadImagesToFirebase();
                    }
                }
            } else {
                ToastUtil.showToast("You haven't picked Image", this);
            }
        } catch (Exception e) {
            ToastUtil.showToast("Something went wrong", this);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * This method is used to upload images to Firebase Storage.
     */
    private void uploadImagesToFirebase() {
        //create storage reference from our app
        //points to the root reference
        StorageReference storageReference = firebaseStorage.getReference();
        //create storage reference for user folder
        //points to the trip folder
        StorageReference userReference = storageReference.child("user/" + firebaseAuth.getCurrentUser().getUid()).child("trips").child("trip" + tripId);
        StorageReference imageReference;
        UploadTask uploadTask;

        //array list used to store images paths
        final ArrayList<String> strings = new ArrayList<>();
        int i = 0;
        for (Uri imageURI : imageURIs) {

            //create storage reference for user's image folder
            //points to the images folder
            imageReference = userReference.child("images/" + "img" + i);
            i++;
            uploadTask = imageReference.putFile(imageURI);
            strings.add(imageURI.getPath());
            // Register observers to listen for when the download is done or if it fails
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, strings);
                    lvMedia.setAdapter(adapter);
                }
            });

            databaseReference.child("users").child(firebaseAuth.getUid()).child("trips").child("trip" + tripId).child("images").child("img" + i).setValue(imageReference.toString());
        }
    }

    /**
     * @param view This method saves the Trip object to firebase database.
     */
    public void saveTrip(View view) {
        String title = null;
        String description = null;
        boolean ok;

        if ((!etTitle.getText().toString().isEmpty()) &&
                (!etDescription.getText().toString().isEmpty()) &&
                (imageURIs.size() != 0) &&
                (placesAdded)) {
            title = etTitle.getText().toString();
            description = etDescription.getText().toString();
            ok = true;
            placesAdded = false;
        } else {
            ok = false;
        }

        if (ok) {
            trip.setTitle(title);
            trip.setDescription(description);
            trip.setDate(date);
            databaseReference.child("users").child(firebaseAuth.getUid()).child("trips").child("trip" + tripId).child("title").setValue(trip.getTitle());
            databaseReference.child("users").child(firebaseAuth.getUid()).child("trips").child("trip" + tripId).child("description").setValue(trip.getDescription());
            databaseReference.child("users").child(firebaseAuth.getUid()).child("trips").child("trip" + tripId).child("date").setValue(trip.getDate());
            tripId++;
            databaseReference.child("users").child(firebaseAuth.getUid()).child("tripNumber").setValue(tripId);

            ToastUtil.showToast("Trip saved!", getApplicationContext());

            Log.d(TripAdderActivity.class.getSimpleName(), "Current trip id = " + tripId);
            Intent intentRecentTrips = new Intent(this, TripListActivity.class);
            intentRecentTrips.putExtra("tripId", tripId);
            startActivity(intentRecentTrips);
        } else {
            ToastUtil.showToast("Trip couldn't be saved! Please check fields!", getApplicationContext());
        }

    }
}

MapsAdderActivity.java

public class MapsAdderActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private List<Place> places;
    private Place place;
    private int placeId = 0;
    private long tripId;

    private DatabaseReference databaseReference;
    private FirebaseAuth firebaseAuth;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps_adder);

        //array list used to store the places added
        places = new ArrayList<>();

        //get database reference
        databaseReference = FirebaseDatabase.getInstance().getReference();

        //create instance of firebase auth
        firebaseAuth = FirebaseAuth.getInstance();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            tripId = bundle.getLong("tripId");
        }

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        //move the camera to the center of the map
        mMap = googleMap;
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(0, 0)));

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Setting the title for the marker.
                // This will be displayed on taping the marker
                markerOptions.title(latLng.latitude + " : " + latLng.longitude);

                // Clears the previously touched position
                mMap.clear();

                // Animating to the touched position
                mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                // Placing a marker on the touched position
                mMap.addMarker(markerOptions);
                place = new Place(Double.toString(latLng.latitude), Double.toString(latLng.longitude));
            }
        });
    }

    public void addMarkerToMap(View view) {
        places.add(place);
    }

    public void saveMarkers(View view) {
        for (int i = placeId; i < places.size(); i++) {
            writeNewPlace(places.get(i).getLat(), places.get(i).getLng());
        }
        TripAdderActivity.placesAdded = true;
        ToastUtil.showToast("Places added!", getApplicationContext());
    }

    private void writeNewPlace(String lat, String lng) {
        Place place = new Place(lat, lng);
        databaseReference.child("users").child(firebaseAuth.getUid()).child("trips").child("trip" + tripId).child("places").child(String.valueOf(placeId)).setValue(place);
        placeId++;
    }

    public void cleanMarkers(View view) {
        places.clear();
        placeId = 0;
        databaseReference.child("users").child(firebaseAuth.getUid()).child("trips").child("trip" + tripId).child("places").removeValue();
    }
}

activity_maps_adder.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:orientation="vertical"
    android:scrollbars="none"
    tools:context=".MapsAdderActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            android:padding="8dp">

            <fragment
                android:id="@+id/map"
                android:name="com.google.android.gms.maps.SupportMapFragment"
                android:layout_width="match_parent"
                android:layout_height="400dp"
                tools:context=".MapsAdderActivity" />
        </FrameLayout>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="addMarkerToMap"
            android:text="@string/add_marker" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="cleanMarkers"
            android:text="@string/clean_markers" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="saveMarkers"
            android:text="@string/save_markers" />
    </LinearLayout>
</ScrollView>

问题是由 MapsAdderActivity 中的 saveMarkers 按钮引起的。

事情应该如何运作:

假设应用程序以 TripListActivity 开头(在此之前我有一个登录 Activity 正常运行)。通过从菜单中按按钮 添加行程,您将被重定向到 TripAdderActivity。从这里您可以将地点添加到您的新旅行中(它们将存储在 Firebase 数据库中)。按 Add places 按钮将带您到 MapsAdderActivity。您应该通过点击屏幕在 googleMap 上添加标记,Add marker 只是将标记保存在列表中,而 Save markers 将保存它们在 Firebase 数据库中。

我得到的错误:

如果我尝试添加更多标记(比如两个,所以我将两个位置对象添加到 places 列表中)并保存它们,按 Save markers 按钮将导致MapsAdderActivity 完成(或类似的东西)。此外,如果 MapsAdderActivity 完成,应用程序应该返回到 TripAdderActivity(从我的角度来看),但它返回到我所在的 TripListActivity出现逻辑错误并崩溃(每次旅行都需要一张图片,不上传会导致错误)。

所以按保存标记(saveMarkers 方法)会以某种方式将我重定向到TripListActivity

Here是对事物如何演变的记录。

在后端一切正常,标记已保存:

正如您在 trip2 中看到的那样,有 2 个正确的“放置”对象。

08-06 17:08:24.110 3293-3293/com.grrigore.tripback_up E/onStart ------: TripListActivity: onStart()
08-06 17:08:24.125 3293-3293/com.grrigore.tripback_up E/onResume ------: TripListActivity: onResume()
08-06 17:08:29.832 3293-3293/com.grrigore.tripback_up E/onPause ------: TripListActivity: onPause()
08-06 17:08:29.916 3293-3293/com.grrigore.tripback_up E/onStart ------: TripAdderActivity: onStart()
08-06 17:08:29.921 3293-3293/com.grrigore.tripback_up E/onResume ------: TripAdderActivity: onResume()
08-06 17:08:30.479 3293-3293/com.grrigore.tripback_up E/onStop ------: TripListActivity: onStop()
08-06 17:08:38.158 3293-3293/com.grrigore.tripback_up E/onPause ------: TripAdderActivity: onPause()
08-06 17:08:38.806 3293-3293/com.grrigore.tripback_up E/art: The String#value field is not present on Android versions >= 6.0
08-06 17:08:39.281 3293-3293/com.grrigore.tripback_up E/onStart ------: MapsAdderActivity: onStart()
08-06 17:08:39.286 3293-3293/com.grrigore.tripback_up E/onResume ------: MapsAdderActivity: onResume()
08-06 17:08:39.943 3293-3293/com.grrigore.tripback_up E/onStop ------: TripAdderActivity: onStop()
08-06 17:09:06.030 3293-3293/com.grrigore.tripback_up E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.grrigore.tripback_up, PID: 3293
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.get(ArrayList.java:411)
        at com.grrigore.tripback_up.TripListActivity$1.onDataChange(TripListActivity.java:119)
        at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
        at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
        at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6816)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)

这次崩溃是因为我没有将图像添加到我的 trip 对象,它会尝试获取列表中的第一张图像,但列表中没有对象。

应用程序崩溃的原因很明显,但我不理解这种行为(在按下 Save markers 按钮时关闭当前 Activity )。

有什么想法吗?

LE: 即使我只添加一个地方,我似乎也得到了错误。事实上,我正在更新地点并没有导致崩溃。

最佳答案

onDataChange 如果您在使用完监听器后没有移除它,它将继续被调用。完成后,您需要删除 onDataChange 监听器,否则会出现您描述的奇怪行为。

您可以通过调用将其删除

databaseReference.removeEventListener(this);

在回调中

关于android - 在 firebase 中使用数据库时按下按钮会导致无法解释的 'redirect',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51708641/

有关android - 在 firebase 中使用数据库时按下按钮会导致无法解释的 'redirect'的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐